以编程方式将图像添加到fabricJS中的画布

时间:2015-02-12 16:12:23

标签: fabricjs

我有一个要添加到fabricJS画布的图像。用户将指定在画布上添加相同图像的次数。

当我循环浏览用户输入的次数并使用fabric.Image.fromURL添加时,它只会添加一次而只会添加到最后一个位置。

编辑:

Here is the jsfiddle on what I am trying to do
http://jsfiddle.net/apsixion/9g0Lfydw/3/

1 个答案:

答案 0 :(得分:0)

以下是我今天如何解决它... 移动代码将图像绘制到外部的不同函数并调用函数。可能不是最理想的解决方案,但对我有用。

// create a wrapper around native canvas element (with id="c")
var canvas = new fabric.Canvas('c', {
    selection: false
});

function drawRectangles(number) {

    i = 0;
    var pic =
        "http://depts.washington.edu/hplab/wordpress/wp-content/uploads/2014/10/smiley-e1415084033498.jpeg";
    for (var i = 0; i < number; i++) {
        var rect = new fabric.Rect({
            left: 5 + i * 160,
            top: 10,
            width: 150,
            height: 150,
            lockRotation: true,
            lockMovementX: false,
            lockMovementY: false
        });
        canvas.add(rect);
    }
    for (var k = 0; k < number; k++) {
        drawStars(k);
    }
}

function drawStars(k) {
    var picStars =
        "http://reviews.babymonitorsdirect.co.uk/images/5-stars.jpg";

    fabric.Image.fromURL(picStars, function (img2) {

        img2.set({
            lockRotation: true,
            lockMovementX: true,
            lockMovementY: true,
            left: 5 + k * 160,
            top: 10,
            width: 50,
            height: 50,
            lockScalingX: true,
            lockScalingY: true,
            selectable: true,
            hasControls: false
        });
        canvas.add(img2);

    });

}
drawRectangles(5);

http://jsfiddle.net/apsixion/z6dq0dp9/2/