Canvas How to - Shrink and enlarge circle








Question

We would like to know how to shrink and enlarge circle.

Answer


<!--from   w  w  w. j av a2s  .c o  m-->
<!-- 
code revised from
http://stackoverflow.com/questions/14455694/circle-animation/14457059#14457059
-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');
  var centerX = canvas.width / 2;
  var centerY = canvas.height / 2;
  var radius = 70;
  setInterval(function () {
      period = 1000; // [miliseconds]
      var linearMod = Date.now() % period / period; // this goes from 0 to 1
      var mod = Math.sin(linearMod * Math.PI); // and here with simple easing we create some bouncing
      var r = radius * mod; // voila
      canvas.width = canvas.width; // ugly dirty clean :)
      context.beginPath();
      context.arc(centerX, centerY, r, 0, 2 * Math.PI, false);
      context.fillStyle = 'green';
      context.fill();
      context.lineWidth = 5;
      context.strokeStyle = '#003300';
      context.stroke();
  }, 25);
}//]]>  
</script>
</head>
<body>
  <canvas id="myCanvas" width="578" height="200"></canvas>
</body>
</html>

The code above is rendered as follows: