Last active
November 25, 2022 13:56
-
-
Save brahimmachkouri/dfbd8906315693fbf1b7f724d4ba45ab to your computer and use it in GitHub Desktop.
Fabric.js : how to draw a rectangle with the mouse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> | |
<title>fabric Creating rect with a mouse</title> | |
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> | |
<meta name="robots" content="noindex, nofollow"> | |
<meta name="googlebot" content="noindex, nofollow"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.2.4/fabric.min.js"></script> | |
</head> | |
<body> | |
<canvas id="c" width="500" height="500" style="border:1px solid #ccc"></canvas> | |
<script type="text/javascript"> | |
var canvas = new fabric.Canvas('c', { | |
selection: false | |
}); | |
var rect, isDown, origX, origY; | |
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) { | |
rect.setCoords(); | |
// désactive la fonction de dessin | |
canvas.off('mouse:down').off('mouse:move').off('mouse:up') | |
isDown = false; | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment