Canvas How to - Move along with a circle








Question

We would like to know how to move along with a circle.

Answer


<!-- w  w w.  j a  v a 2 s . c  om-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
(function(){
    var ctx = document.getElementById("canvas").getContext("2d"),
        x = 150,
        y = 180,
        angle = 0,
        velX = 0,
        velY = 0,
        thrust = 3;
    function draw(){
        velX = Math.cos(angle * Math.PI / 180) * thrust;
        velY = Math.sin(angle * Math.PI / 180) * thrust;
        x += velX;
        y += velY;
        angle+=2;
        ctx.fillStyle = "#fff";
        ctx.clearRect(0,0,400,400);
        ctx.beginPath();
        ctx.rect(x, y, 10, 10);
        ctx.closePath();
        ctx.fill();
        setTimeout(function(){draw()}, 30);   
    }
    draw();
})();
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width="400" height="400" style="background:#000;"></canvas>
</body>
</html>

The code above is rendered as follows: