Canvas How to - Move object in straight line








Question

We would like to know how to move object in straight line.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-2.0.2.js'></script>
<script type='text/javascript'>
$(window).load(function(){<!--  www .j a  v  a  2s. co m-->
$(function () {
    var c = document.getElementsByTagName('canvas')[0].getContext('2d'),
        x = 0,
        y = 0;
    function update() {
        x += 0.1;
        y += 0.1;
        if (x > 50) {
            killTheGame();return;
        }
        draw();
    }
    function draw() {
        c.clearRect(0, 0, c.canvas.width, c.canvas.height);
        c.fillStyle = 'red';
        c.fillRect(x, y, 10, 10);
    }
    function killTheGame() {
        console.log('kill');
        webkitCancelRequestAnimationFrame(id);
    }
    var id = null;
    (function tick () {
        console.log('tick');
        id = webkitRequestAnimationFrame(tick);
        update();
    }());
});
});
</script>
</head>
<body>
  <canvas width='200'height'200'></canvas>
</body>
</html>

The code above is rendered as follows: