increment the rotation angle for an object in HTML5 canvas? - Javascript Canvas

Javascript examples for Canvas:Object

Description

increment the rotation angle for an object in HTML5 canvas?

Demo Code

ResultView the demo in separate window

<!doctype html>
<html>
   <head> 
      <!-- reset css --> 
      <script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script> 
      <style>

body{ background-color: ivory; }
#canvas{border:1px solid red;}

      </style> 
      <script>
$(function(){/*from w w w. ja  v a2 s  . c o  m*/
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;
    var $canvas=$("#canvas");
    var canvasOffset=$canvas.offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;
    ctx.lineWidth=10;
    var cx=canvas.width/2;
    var cy=canvas.height/2;
    var lineLength = 90;
    $("#canvas").mousemove(function(e){handleMouseMove(e);});
    function draw(angle){
        ctx.clearRect(0,0,cw,ch);
        ctx.save();
        // draw unrotated line
        ctx.beginPath();
        ctx.moveTo(cx-lineLength/2,cy)
        ctx.lineTo(cx+lineLength/2,cy);
        ctx.strokeStyle='red';
        ctx.stroke();
        // draw rotated line
        ctx.translate(cx,cy);
        ctx.rotate(angle) ;
        ctx.beginPath();
        ctx.moveTo(-lineLength/2,0)
        ctx.lineTo(lineLength/2,0);
        ctx.strokeStyle='orange';
        ctx.stroke();
        ctx.restore();
    }
    function handleMouseMove(e){
      e.preventDefault();
      e.stopPropagation();
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      // Put your mousemove stuff here
      var dx=mouseX-cx;
      var dy=mouseY-cy;
      var radianAngle=Math.atan2(dy,dx);
      draw(radianAngle);
    }
}); // end $(function(){});

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

Related Tutorials