Draw arrow on canvas tag

后端 未结 12 944
小鲜肉
小鲜肉 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 14:00

    Here is the working solution

    function draw_arrow(ctx,fx,fy,tx,ty){ //ctx is the context
        var angle=Math.atan2(ty-fy,tx-fx);
        ctx.moveTo(fx,fy); ctx.lineTo(tx,ty);
        var w=3.5; //width of arrow to one side. 7 pixels wide arrow is pretty
        ctx.strokeStyle="#4d4d4d"; ctx.fillStyle="#4d4d4d";
        angle=angle+Math.PI/2; tx=tx+w*Math.cos(angle); ty=ty+w*Math.sin(angle);
        ctx.lineTo(tx,ty);
      //Drawing an isosceles triangle of sides proportional to 2:7:2
        angle=angle-1.849096; tx=tx+w*3.5*Math.cos(angle); ty=ty+w*3.5*Math.sin(angle);
        ctx.lineTo(tx,ty);
        angle=angle-2.584993; tx=tx+w*3.5*Math.cos(angle); ty=ty+w*3.5*Math.sin(angle);
        ctx.lineTo(tx,ty);
        angle=angle-1.849096; tx=tx+w*Math.cos(angle); ty=ty+w*Math.sin(angle);
        ctx.lineTo(tx,ty);
        ctx.stroke(); ctx.fill();
    }
    

提交回复
热议问题