Skip to content

Instantly share code, notes, and snippets.

@brahimmachkouri
Last active November 25, 2022 13:56
Show Gist options
  • Save brahimmachkouri/dfbd8906315693fbf1b7f724d4ba45ab to your computer and use it in GitHub Desktop.
Save brahimmachkouri/dfbd8906315693fbf1b7f724d4ba45ab to your computer and use it in GitHub Desktop.
Fabric.js : how to draw a rectangle with the mouse
<!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