Canvas How to - Draw random shape in animation








Question

We would like to know how to draw random shape in animation.

Answer


<!--  w ww .j  av  a 2 s.c o  m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var ctx, canvas;
    function setup(){
      canvas = document.createElement("canvas");
      canvas.width = 500;
      canvas.height = 300;
      canvas.style.border = "solid 1px";
      ctx = canvas.getContext("2d");
      document.body.appendChild(canvas);
    }
    function draw() {
      window.requestAnimationFrame(draw); 
      var ranX = Math.random()*400;
      var ranY = Math.random()*300;
      var ranColor = '#'+Math.floor(Math.random()*16777215).toString(16);
      ctx.fillStyle = ranColor;
      ctx.beginPath();
      ctx.moveTo(100,100);
      ctx.lineTo(250,75);
      ctx.lineTo(ranX,ranY);
      ctx.fill();
      ctx.closePath(); 
    }
    setup();
    draw();
}//]]>  
</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: