Canvas How to - Draw two flying circles on two canvas








Question

We would like to know how to draw two flying circles on two canvas.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--from ww  w.j  av  a2s.  com-->
function Animate(id, useTime){
    var can = document.getElementById(id),
        ctx = can.getContext('2d'),
        wid = can.width,
        hei = can.height,
        lst = Date.now(),
        rps = 2*Math.PI,
        step = rps/60,
        ang = 0;
    (function draw(){
        var dif = Date.now() - lst;
        lst = Date.now();
        if (useTime) step = rps * dif/1000;
        ang += step;
        ctx.clearRect(0,0,wid,hei);
        ctx.beginPath();
        ctx.arc(wid/2 + Math.cos(ang)*50, hei/2 + Math.sin(ang)*50, 10, 0, 2*Math.PI);
        ctx.fill();
        webkitRequestAnimationFrame(draw);
    })();
}
Animate('can1', false);
Animate('can2', true);
}//]]>  
</script>
</head>
<body>
  <canvas id="can1" width="200" height="200"></canvas>
  <canvas id="can2" width="200" height="200"></canvas>
</body>
</html>

The code above is rendered as follows: