FabricJS draw arrow!
by brightertools
HTML
<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="600" height="600"></canvas>
CSS
canvas {
border: 1px solid #999;
}
JavaScript
var canvas = this.__canvas = new fabric.Canvas('c');
canvas.selection = false;
function drawArrow(fromx, fromy, tox, toy) {
var angle = Math.atan2(toy - fromy, tox - fromx);
var headlen = 30; // arrow head size
// bring the line end back some to account for arrow head.
tox = tox - (headlen) * Math.cos(angle);
toy = toy - (headlen) * Math.sin(angle);
// calculate the points.
var points = [
{
x: fromx, // start point
y: fromy
}, {
x: fromx - (headlen / 4) * Math.cos(angle - Math.PI / 2),
y: fromy - (headlen / 4) * Math.sin(angle - Math.PI / 2)
},{
x: tox - (headlen / 4) * Math.cos(angle - Math.PI / 2),
y: toy - (headlen / 4) * Math.sin(angle - Math.PI / 2)
}, {
x: tox - (headlen) * Math.cos(angle - Math.PI / 2),
y: toy - (headlen) * Math.sin(angle - Math.PI / 2)
},{
x: tox + (headlen) * Math.cos(angle), // tip
y: toy + (headlen) * Math.sin(angle)
}, {
x: tox - (headlen) * Math.cos(angle + Math.PI / 2),
y: toy - (headlen) * Math.sin(angle + Math.PI / 2)
}, {
x: tox - (headlen / 4) * Math.cos(angle + Math.PI / 2),
y: toy - (headlen / 4) * Math.sin(angle + Math.PI / 2)
}, {
x: fromx - (headlen / 4) * Math.cos(angle + Math.PI / 2),
y: fromy - (headlen / 4) * Math.sin(angle + Math.PI / 2)
},{
x: fromx,
y: fromy
}
];
var pline = new fabric.Polyline(points, {
fill: 'white',
stroke: 'black',
opacity: 1,
strokeWidth: 2,
originX: 'left',
originY: 'top',
selectable: true
});
canvas.add(pline);
canvas.renderAll();
}
//draw an arrow!
drawArrow(100, 100, 150, 150);
// click and drag to draw more arrow!
var startX, startY, endX, endY;
canvas.on('mouse:down', function(e) {
var pointer = canvas.getPointer(event.e);
startX = pointer.x;
startY = pointer.y;
});
canvas.on('mouse:up', function() {
var pointer = canvas.getPointer(event.e);
endX = pointer.x;
endY = pointer.y;
drawArrow(startX, startY, endX, endY);
});