Shadow - Fabric.js
HTML
Click several times on the canvas, then press Esc to end the polyline<br/><br/>
Problem: after selecting/unselecting the line several times and moving it around, the selection is unstable (clicking on the line doesn't select the polyline or clicking outside the lines selects it)
<canvas id="c" width="400" height="300"></canvas>
JavaScript
var canvas = window._canvas = new fabric.Canvas('c');
var blueRect = new fabric.Rect({
top: 10,
left: 10,
width: 20,
height: 20,
fill: 'blue'
});
canvas.add(blueRect);
// define hide/unhide methods
fabric.Object.prototype.hide = function() {
this.set({
opacity: 0,
selectable: false
});
};
fabric.Object.prototype.show = function() {
this.set({
opacity: 1,
selectable: true
});
};
var x = 0, y = 0;
var drawing = true;
var lastRect = null;
var polyline = null;
canvas.observe("mouse:down", function (e) {
if (drawing)
drawPolyline(e);
else
seePolyline(e);
});
var drawPolyline = function(e) {
var pos = canvas.getPointer(e.e);
var rect = new fabric.Rect({
top: pos.y,
left: pos.x,
width: 7,
height: 7,
fill: '#ffffff',
strokeWidth: 1,
stroke: 'rgb(163,194,255)'
});
rect.hasControls = rect.hasBorders = false;
canvas.add(rect);
canvas.bringToFront(rect)
var line = null;
if (lastRect === null) {
firstPolylineRec = rect;
}
else {
var coords = [ x, y, pos.x, pos.y ];
line = new fabric.Line(coords, {
fill: 'black',
stroke: 'black',
strokeWidth: 3,
selectable: false
});
line.hasControls = line.hasBorders = false;
canvas.add(line);
canvas.sendToBack(line)
}
if (line) {
rect.line1 = line;
lastRect.line2 = line;
line.rect1 = lastRect;
line.rect2 = rect;
}
x = pos.x;
y = pos.y;
lastRect = rect;
};
canvas.on('object:moving', function(e) {
var rect = e.target;
rect.line1 && rect.line1.set({ 'x2': rect.left, 'y2': rect.top });
rect.line2 && rect.line2.set({ 'x1': rect.left, 'y1': rect.top });
canvas.renderAll();
});
fabric.util.addListener(window, 'keyup', function (e) {
if (e.keyCode === 27) { // esc key was pressed
drawing = false;
deselectAll();
canvas.renderAll();
}
});
// selects/deselects polyline(s)
var seePolyline = function(e) {
...