fabric Creating rect with a mouse
fabric Creating rect with a mouse
by 20yco
HTML
<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="800" height="300" style="border: 1px solid red"></canvas>
JavaScript
var rect, isDown, origX, origY;
var canvas = new fabric.Canvas('c', {
selection: false
});
setTimeout(function() {
// Why this "rect" is selectable while others you've draw not????
var rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'green',
width: 50,
height: 50,
transparentCorners: false,
selectable: false
});
canvas.add(rect);
canvas.renderAll();
}, 100);
canvas.on('mouse:down', function(o) {
isDown = true;
var pointer = canvas.getPointer(o.e);
origX = pointer.x;
origY = pointer.y;
var pointer = canvas.getPointer(o.e);
rect = new fabric.Rect({
left: origX,
top: origY,
originX: 'left',
originY: 'top',
width: pointer.x - origX,
height: pointer.y - origY,
angle: 0,
fill: 'rgba(255,0,0,0.5)',
transparentCorners: false
});
canvas.add(rect);
});
canvas.on('mouse:move', function(o) {
if (!isDown) return;
var pointer = canvas.getPointer(o.e);
if (origX > pointer.x) {
rect.set({
left: Math.abs(pointer.x)
});
}
if (origY > pointer.y) {
rect.set({
top: Math.abs(pointer.y)
});
}
rect.set({
width: Math.abs(origX - pointer.x)
});
rect.set({
height: Math.abs(origY - pointer.y)
});
canvas.renderAll();
});
canvas.on('mouse:up', function(o) {
isDown = false;
});