New Fabric JS上的拖放图像问题

时间:2017-11-23 13:18:48

标签: javascript fabricjs

在最新版本的Fabric JS中,图像丢弃功能无法正常工作。

    function handleDrop(e) {
        e.preventDefault();
        // this / e.target is current target element.

        if (e.stopPropagation) {
            e.stopPropagation(); // stops the browser from redirecting.
        }

        var obj = document.querySelector('#draggable_items_container .drag_item.draggable_items');

        if($(obj).attr('data-type')=='image')
        {
            var image_url = $(obj).attr('data-value');
            var new_image = new fabric.Image(obj, {
                width: obj.width,
                height: obj.height,
                left: e.layerX,
                top: e.layerY,
            });
            canvas.add(new_image);
        }
        else
        {
            var text_value = $(obj).attr('data-value');
            if(text_value=='')
            {
                alert('You cant drag blank text');
                return false;
            }

            var params = {
                canvas_obj : canvas,
                text: text_value,
                left : e.layerX,
                top : e.layerY,
                font_size : 22,
                editable: false,
            };
            add_text_canvas(params);
        }
        return false;
    }

工作小提琴:
http://jsfiddle.net/Ahammadalipk/w8kkc/185/

不适用于2.0.0-beta.7

http://jsfiddle.net/dhavalsisodiya/w8kkc/412/

那么如何解决这个问题?

enter image description here

1 个答案:

答案 0 :(得分:2)

var newImage = new fabric.Image(img, {
    width: img.naturalWidth,
    height: img.naturalHeight,
    scaleX: setImageWidth/img.naturalWidth,        
    scaleY: setImageHeight/img.naturalHeight,
    // Set the center of the new object based on the event coordinates relative
    // to the canvas container.
    left: e.layerX,
    top: e.layerY
});

您需要设置图像的实际宽度和高度,然后根据您的要求缩放X和Y.此处已更新fiddle