Draw arrow on canvas tag

后端 未结 12 911
小鲜肉
小鲜肉 2020-11-27 13:50

I want to draw an arrow using the canvas tag, javascript. I\'ve made it using the quadratic function, but I\'m having problems to calculate the angle of rotation of the arro

12条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 13:57

    This code is similar to Titus Cieslewski's solution, maybe the arrow is a bit nicer:

    function canvasDrawArrow(context, fromx, fromy, tox, toy) {
        var headlen = 10.0;
        var back = 4.0;
        var angle1 = Math.PI / 13.0;
        var angle2 = Math.atan2(toy - fromy, tox - fromx);
        var diff1 = angle2 - angle1;
        var diff2 = angle2 + angle1;
        var xx = getBack(back, fromx, fromy, tox, toy);
        var yy = getBack(back, fromy, fromx, toy, tox);
    
        context.moveTo(fromx, fromy);
        context.lineTo(tox, toy);
    
        context.moveTo(xx, yy);
        context.lineTo(xx - headlen * Math.cos(diff1), yy - headlen * Math.sin(diff1));
    
        context.moveTo(xx, yy);
        context.lineTo(xx - headlen * Math.cos(diff2), yy - headlen * Math.sin(diff2));
    }
    
    function getBack(len, x1, y1, x2, y2) {
        return x2 - (len * (x2 - x1) / (Math.sqrt(Math.pow(y2 - y1, 2) + Math.pow(x2 - x1, 2))));
    }
    

    this works well with lineWidth > 1. It can come in handy when drawing x and y axis

提交回复
热议问题