【问题标题】:Place image on click of label点击标签放置图片
【发布时间】:2018-07-22 07:02:12
【问题描述】:

我在画布中有一个图像放置功能。如果用户单击图像,则会将图像拖放到画布上。现在,我想在点击标签时做同样的事情。但由于标签没有 naturalWidth 和 naturalHeight,所以它不起作用。

对于下面的 HTML,如果用户点击 标签它的工作,但不是点击(添加产品图片或添加二维码)。

HTML

<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>

jQuery

/* 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();
    });

控制台输出

点击标签

类{filters: Array(0), width: undefined, dirty: true, height: undefined, scaleX: NaN, ...}

点击图片:

类{filters: Array(0), width: 100, dirty: true, height: 100, scaleX: 1, ...}

【问题讨论】:

    标签: javascript jquery fabricjs


    【解决方案1】:

    问题是当被点击的元素是img时,obj将是Node,但当被点击的元素是span时,它将是一个jQuery对象。

    您必须这样做,以便在两种情况下都使用相同类型的对象:

    if($(obj).attr('data-action')=='span'){
        var obj = $(this).parent().find('img').get(0);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-16
      • 2014-04-14
      相关资源
      最近更新 更多