canvas arcTo method usage - Javascript Canvas

Javascript examples for Canvas:Arc

Description

canvas arcTo method usage

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>Canvas arcTo problem</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-git.js"></script> 
      <script type="text/javascript" src="http://getfirebug.com/firebug-lite-debug.js"></script> 
      <script type="text/javascript">
    $(window).on('load', function() {
function Point(x, y){/*  w w  w. j  a  v  a 2 s . c  o  m*/
    this.x = x ? x : 0;
    this.y = y ? y : 0;
    this.translate=translate;
    this.rotate=rotate;
}
    var ctx,
        canvas = document.getElementById('canvas');
    canvas.width = 600;
    canvas.height = 600;
    ctx = canvas.getContext('2d');
    ctx.lineWidth = 2;
    draw(ctx, new Point(150,50), new Point(50, 50), new Point(150, 270) );
    draw(ctx, new Point(150,50), new Point(50, 50), new Point(-50, 370) );
    draw(ctx, new Point(300,200), new Point(100,100), new Point(200, 300) );
    draw(ctx, new Point(150,300), new Point(50,100), new Point(250, 200) );
function translate(t){
    var x=this.x+t.x;
    var y=this.y+t.y;
    return new Point(x,y);
}
function rotate(theta){
    var x=this.x*Math.cos(theta)+this.y*Math.sin(theta);
    var y=this.y*Math.cos(theta)-this.x*Math.sin(theta);
    return new Point(x,y);
}
function draw(ctx, p1, p2, p3){
    var k1, k, r=38;
    var q1,q2,q3;
    var g1,g2,t1,t2;
    k1 = Math.atan2(p1.y - p2.y, p1.x - p2.x);

    q2=new Point(-p2.x,-p2.y);
    q1=p1.translate(q2).rotate(k1);
    q3=p3.translate(q2).rotate(k1);
    if(q3.y<0){ //swap p1 and p3
    var temp=new Point(p1.x,p1.y);
        p1=new Point(p3.x,p3.y);
        p3=new Point(temp.x,temp.y);
        k1 = Math.atan2(p1.y - p2.y, p1.x - p2.x);
        q1=p1.translate(q2).rotate(k1);
        q3=p3.translate(q2).rotate(k1);
    }
    k = Math.atan2(q3.y, q3.x);
    k /= 2;

    g1=new Point(r/Math.tan(k), 0);
    g2=new Point(r*Math.cos(2*k)/Math.tan(k), r*Math.sin(2*k)/Math.tan(k));

    t1=g1.rotate(-k1).translate(p2);
    t2=g2.rotate(-k1).translate(p2);
    ctx.moveTo(p1.x, p1.y);
    ctx.lineTo(t1.x, t1.y); // lineTo the point of tangency
    ctx.arcTo(p2.x, p2.y, t2.x, t2.y, r ); // then arc
    ctx.lineTo(p3.x, p3.y); // till p3
    ctx.stroke();
}
    });

      </script> 
   </head> 
   <body> 
      <canvas id="canvas" style="width:600px; height:600px; margin: 0 auto; background-color: yellow; " ;></canvas>  
   </body>
</html>

Related Tutorials