Javascript examples for Canvas:Object
collision or intersection detection of canvas objects
<html> <head> <title>Snapping of objects</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script> <script type="text/javascript"> window.onload=function(){/*from w w w . ja v a 2s . c om*/ window.canvas = new fabric.Canvas('fabriccanvas'); window.counter = 0; var newleft = 0; var edgedetection = 40; //pixels to snap canvas.selection = false; plusrect(); plusrect(); plusrect(); function plusrect(top, left, width, height, fill) { window.canvas.add(new fabric.Rect({ top: 300, name: 'rectangle ' + window.counter, left: 0 + newleft, width: 100, height: 100, fill: 'rgba(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ', 0.75)', lockRotation: true, originX: 'left', originY: 'top', cornerSize: 15, hasRotatingPoint: false, perPixelTargetFind: true, minScaleLimit: 1, maxHeight: document.getElementById("fabriccanvas").height, maxWidth: document.getElementById("fabriccanvas").width, })); window.counter++; newleft += 200; } this.canvas.on('object:moving', function (e) { var obj = e.target; obj.setCoords(); //Sets corner position coordinates based on current angle, width and height canvas.forEachObject(function (targ) { activeObject = canvas.getActiveObject(); if (targ === activeObject) return; if (Math.abs(activeObject.oCoords.tr.x - targ.oCoords.tl.x) < edgedetection) { activeObject.left = targ.left - activeObject.currentWidth; } if (Math.abs(activeObject.oCoords.tl.x - targ.oCoords.tr.x) < edgedetection) { activeObject.left = targ.left + targ.currentWidth; } if (Math.abs(activeObject.oCoords.br.y - targ.oCoords.tr.y) < edgedetection) { activeObject.top = targ.top - activeObject.currentHeight; } if (Math.abs(targ.oCoords.br.y - activeObject.oCoords.tr.y) < edgedetection) { activeObject.top = targ.top + targ.currentHeight; } if (activeObject.intersectsWithObject(targ) && targ.intersectsWithObject(activeObject)) { targ.strokeWidth = 10; targ.stroke = 'red'; } else { targ.strokeWidth = 0; targ.stroke = false; } if (!activeObject.intersectsWithObject(targ)) { activeObject.strokeWidth = 0; activeObject.stroke = false; } }); }); } </script> </head> <body> <canvas id="fabriccanvas" width="800" height="500" style="border:1px solid #ccc"></canvas> </body> </html>