Skip to content

Instantly share code, notes, and snippets.

@farnabaz
Created May 22, 2015 23:29
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save farnabaz/175bb89fbeaec3e1b0e0 to your computer and use it in GitHub Desktop.
Save farnabaz/175bb89fbeaec3e1b0e0 to your computer and use it in GitHub Desktop.
fabric.js arrow shape
//
// Arrow for fabric.js
//
(function($){
$.Arrow = $.util.createClass($.Line, $.Observable, {
initialize: function(e,t) {
this.callSuper("initialize", e, t)
this.set({type:'arrow'});
},
_render: function(e) {
e.beginPath();
var r = this.calcLinePoints();
var headlen = 8; // length of head in pixels
var angle = Math.atan2(r.y2-r.y1,r.x2-r.x1);
e.moveTo(r.x1, r.y1);
e.lineTo(r.x2, r.y2);
e.lineTo(r.x2-headlen*Math.cos(angle-Math.PI/6),r.y2-headlen*Math.sin(angle-Math.PI/6));
e.moveTo(r.x2, r.y2);
e.lineTo(r.x2-headlen*Math.cos(angle+Math.PI/6),r.y2-headlen*Math.sin(angle+Math.PI/6));
e.lineWidth = this.strokeWidth;
var s = e.strokeStyle;
e.strokeStyle = this.stroke || e.fillStyle, this.stroke && this._renderStroke(e), e.strokeStyle = s
},
complexity: function() {
return 2
}
});
$.Arrow.fromObject = function(e) {
var n = [e.x1, e.y1, e.x2, e.y2];
return new $.Arrow(n, e)
}
})(fabric);
@SmboBeast
Copy link

This is great. Thank you for this. By any chance have you figured out the problem with the arrow not appearing when drawing a straight line? I believe it's because the Line class is sets the width and height to just the line. I haven't figured out a way to get it to work by extending the object layer to the size of the arrow.

@monkeytroy
Copy link

I could not get around the width / height problem with this either.. ended up calculating the points to draw a polygon arrow instead. https://jsfiddle.net/6e17oxc3/

@krunal
Copy link

krunal commented Aug 28, 2017

Here is the blog I have written about how to draw an arrow with fabricjs which includes jsfiddle as well. I hope that will help someone.
https://blog.thirdrocktechkno.com/how-to-draw-an-arrow-using-html-5-canvas-and-fabricjs-9500c3f50ecb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment