[英]Draw rectangle with fabric.js
Here is the my code to drawing a rectangle with fabric.js, but i am not getting the exact result. 这是我用fabric.js绘制矩形的代码,但我没有得到确切的结果。 I am using fabric.js to draw a rectangle on the canvas in HTML 我正在使用fabric.js在HTML中的画布上绘制一个矩形
<canvas id="canvas2" width=500 height=500 style="height:500px;width:500px;"></canvas>
my JS code is: 我的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;
});
Shariq Ansari, For my understanding you have a problem to draw a rectangle with mouse. Shariq Ansari,据我了解,用鼠标绘制矩形有问题。 Please check this fiddle 请检查这个小提琴
Your problem was with mouse move. 你的问题是鼠标移动。 This is what you need to do in your mouse:move event: 这是您需要在鼠标中执行的操作:移动事件:
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();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.