Canvas How to - Move rectangle back and forth








Question

We would like to know how to move rectangle back and forth.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--from w  w w.j  ava 2  s .co m-->
var context;
function setupAnimCanvas() {
    var canvas = document.getElementById('assignmenttwoCanvas');
    if (canvas.getContext) {
        ctx = canvas.getContext('2d');
        draw();
    }
}
var startPos = [500, 500];
var endPos = [0, 0];
var dx = -3, dy = -3;
var x = startPos[0], y = startPos[1];
function draw() {
    ctx.clearRect(0, 0, 500, 500);
    ctx.fillRect(x, y, 20, 20);
    x += dx;
    y += dy;
    if (x < endPos[0] || x > startPos[0] ||
        y < endPos[1] || y > startPos[1] ) {
        dx = -dx;
        dy = -dy;
    }
    setTimeout(draw, 16);
}
setupAnimCanvas();
}//]]>  
</script>
</head>
<body>
  <canvas id="assignmenttwoCanvas" width="500" height="500"></canvas>
</body>
</html>

The code above is rendered as follows: