Canvas How to - Enlarge rectangle in animation








Question

We would like to know how to enlarge rectangle in animation.

Answer


<!--from   w ww . j av a 2 s .c  o m-->

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='https://ajax.googleapis.com/ajax/libs/mootools/1.4.1/mootools-nocompat.js'></script>
<script type='text/javascript'>
window.addEvent('load', function() {
    var requestAnimationFrame = 
        requestAnimationFrame ||
        webkitRequestAnimationFrame ||
        mozRequestAnimationFrame ||
        msRequestAnimationFrame ||
        oRequestAnimationFrame;
    var c = document.getElementById('c');
    ctx = c.getContext('2d');
    var x = 100;
    ctx.fillStyle = '#f00';
    function loop() {
        ctx.fillRect(x, 100, 20, 20);
        ++x;
        requestAnimationFrame(loop);
    }
    requestAnimationFrame(loop);
});
</script>
</head>
<body>
  <canvas id="c" width="400" height="400"></canvas>
</body>
</html>

The code above is rendered as follows: