Skip to content Skip to sidebar Skip to footer

Arrows In Fabricjs

I'm trying to create an arrow shape using fabricjs. Thus far my best approach has been to add a line and a triangle and combine them into a composite group. The problem however is,

Solution 1:

I had the same problem and ended up doing math to calculate the points that would make up an arrow shape around a line and using a polygon object instead.

The core of it looks like:

var angle = Math.atan2(toy - fromy, tox - fromx);

var headlen = 15;  // 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
    }
];

Then create a polygon from the points.

https://jsfiddle.net/6e17oxc3/

Solution 2:

What you can do is calculate the new size after the object is stretched and draw another object on the same exact area and removing the previous one.

var obj = canvas.getActiveObject();
var width = obj.getWidth();
var height = obj.getHeight;
var top = obj.getTop();

Now if you have only one object that is stretched, you can simply use the data above to draw another nicely looking object on the canvas. If you have multiples then you need to get the data for all of them and draw them one by one.

Post a Comment for "Arrows In Fabricjs"