Html 5 Canvas complete arrowhead

前端 未结 5 1523
鱼传尺愫
鱼传尺愫 2021-01-14 08:47

I\'m using the wPaint plugin and I am attempting to add a few more features. What I need is a drawn line to end with an \"arrowhead\". I have tried just about everything I c

5条回答
  •  日久生厌
    2021-01-14 09:03

    This is how to create a line object that draws arrowheads on both ends

    The interesting part is calculating the angle of the arrowheads like this:

    var startRadians=Math.atan((this.y2-this.y1)/(this.x2-this.x1));
    startRadians+=((this.x2>=this.x1)?-90:90)*Math.PI/180;
    
    var endRadians=Math.atan((this.y2-this.y1)/(this.x2-this.x1));
    endRadians+=((this.x2>=this.x1)?90:-90)*Math.PI/180;
    

    The rest is just drawing the line and 2 triangles for arrowheads the calculated rotations

    Line.prototype.drawArrowhead=function(ctx,x,y,radians){
        ctx.save();
        ctx.beginPath();
        ctx.translate(x,y);
        ctx.rotate(radians);
        ctx.moveTo(0,0);
        ctx.lineTo(5,20);
        ctx.lineTo(-5,20);
        ctx.closePath();
        ctx.restore();
        ctx.fill();
    }
    

    Here is code and a Fiddle: http://jsfiddle.net/m1erickson/Sg7EZ/

    
    
    
     
    
    
    
    
    
    
    
    
    
        
    
    
    

提交回复
热议问题