Html 5 Canvas complete arrow head - Javascript Canvas

Javascript examples for Canvas:Example

Description

Html 5 Canvas complete arrow head

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script> 
      <style id="compiled-css" type="text/css">

canvas {/*from  w  w w. j ava 2 s .c  om*/
   border:1px solid red;
}


      </style> 
      <script type="text/javascript">
    $(window).load(function(){
        var canvas=document.getElementById("canvas");
        var context=canvas.getContext("2d");
        function Line(x1,y1,x2,y2){
            this.x1=x1;
            this.y1=y1;
            this.x2=x2;
            this.y2=y2;
        }
        Line.prototype.drawWithArrowheads=function(ctx){
            // arbitrary styling
            ctx.strokeStyle="blue";
            ctx.fillStyle="blue";
            ctx.lineWidth=1;
            // draw the line
            ctx.beginPath();
            ctx.moveTo(this.x1,this.y1);
            ctx.lineTo(this.x2,this.y2);
            ctx.stroke();

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

            var endRadians=Math.atan((this.y2-this.y1)/(this.x2-this.x1));
            endRadians+=((this.x2>this.x1)?90:-90)*Math.PI/180;
            this.drawArrowhead(ctx,this.x2,this.y2,endRadians);
        }
        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();
        }

        var line=new Line(50,50,250,275);

        line.drawWithArrowheads(context);
    });

      </script> 
   </head> 
   <body> 
      <canvas id="canvas" width="300" height="300"></canvas>  
   </body>
</html>

Related Tutorials