用fabric.js绘制矩形

时间:2017-02-01 11:58:42

标签: javascript fabricjs

这是我用fabric.js绘制矩形的代码,但我没有得到确切的结果。我正在使用fabric.js在HTML中的画布上绘制一个矩形

<canvas id="canvas2" width=500 height=500 style="height:500px;width:500px;"></canvas>

我的JS代码是:

var canvas = new fabric.Canvas("canvas2");
var rectangle, isDown, origX, origY;

canvas.on('mouse:down', function(o){
    var pointer = canvas.getPointer(o.e);

    isDown = true;
    origX = pointer.x;
    origY = pointer.y;

    rectangle = new fabric.Rect({
        left: origX,
        top: origY,
        fill: '',
        stroke: 'red',
        strokeWidth: 3,
    });
    canvas.add(rectangle);
});

canvas.on('mouse:move', function(o){
    if (!isDown) return;
    var pointer = canvas.getPointer(o.e);
    canvas.renderAll();
});

canvas.on('mouse:up', function(o){
    isDown = false;
});

1 个答案:

答案 0 :(得分:4)

Shariq Ansari, 根据我的理解,使用鼠标绘制矩形会有问题。 请查看此fiddle

你的问题是鼠标移动。这是您需要在鼠标中执行的操作:移动事件:

canvas.on('mouse:move', function(o){
    if (!isDown) return;
    var pointer = canvas.getPointer(o.e);
    if(origX>pointer.x){
        rectangle.set({ left: Math.abs(pointer.x) });
    }
    if(origY>pointer.y){
        rectangle.set({ top: Math.abs(pointer.y) });
    }

    rectangle.set({ width: Math.abs(origX - pointer.x) });
    rectangle.set({ height: Math.abs(origY - pointer.y) });
    canvas.renderAll();
});