我在画布中有一个图像丢弃功能。如果用户点击图像,则将图像放在画布上。现在,我想点击标签做同样的事情。但由于标签没有naturalWidth& naturalHeight,它不起作用。
对于以下HTML,如果用户点击< img />标记其工作,但不点击(添加产品图像或添加QR码)。
<ul class="dropdown-menu drop-bwn-icon image-parent" role="menu">
<li class="img_holder">
<img class="control-label image_drop_class image_drop drag_item canvas-img" data-value="http://localhost/lynkus/uploads/userprofile/image_n.png" data-type="image" width="30" data-width="100" src="http://localhost/lynkus/uploads/userprofile/image_n.png" data-image-name="image_1" draggable="true" alt="verified_image" data-action="image">
<span class="images_title image_drop_class" data-action="span">Add Product Images</span>
</li>
<li class="img_holder">
<img class="control-label image_drop_class image_drop drag_item" data-value="http://localhost/lynkus/uploads/userprofile/qr-code.png" data-type="image" width="30" data-width="260" src="http://localhost/lynkus/uploads/userprofile/qr-code.png" data-image-name="qr_code" draggable="true" alt="verified_image" data-action="image">
<span class="images_title image_drop_class" data-action="span">Add QR Code</span>
</li>
</ul>
/* On click place image on canvas */
$('.image_drop_class').click(function(){
var obj = this;//document.querySelector('.image_drop');
if($(obj).attr('data-action')=='span') // Owverwrite the object
{
var obj = $(this).parent().find('img:first');
}
var t_width = $(obj).attr('data-width');
var setImageWidth = t_width;
var setImageHeight = 100;
var image_url = $(obj).attr('data-value');
var image_id = $(obj).attr('data-image-name');
var new_image = new fabric.Image(obj, {
width: obj.naturalWidth,
height: obj.naturalHeight,
scaleX: setImageWidth/obj.naturalWidth,
scaleY: setImageHeight/obj.naturalHeight,
left: 50,
top: 50,
id: image_id
});
console.log(new_image);
canvas.add(new_image);
canvas.renderAll();
});
点击标签
klass {filters:Array(0),width:undefined,dirty:true,height:undefined,scaleX:NaN,...}
点击图片:
klass {filters:Array(0),width:100,dirty:true,height:100,scaleX:1,...}
答案 0 :(得分:1)
问题是,当点击的元素是img
时,obj
将是Node
,但当点击的元素是span
时,它将是一个jQuery对象
你必须做这样的事情,所以你在两种情况下都使用相同类型的对象:
if($(obj).attr('data-action')=='span'){
var obj = $(this).parent().find('img').get(0);
}