Canvas Animation Border Stop
HTML
<canvas id="canvas" width="500" height="400" style="border:1px solid #000000;"></canvas>
JavaScript
// get the theory behind:
// http://nepraunig.com/wp/?p=34
// grab the canvas and context
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// inital coordinates of the black square
var x = 0;
var y = 50;
// speed of the movement
// initially 1, means it increases the x value
var speed = 1;
// width and height of the square
var width = 100;
var height = 100;
function animate() {
// clear
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw
ctx.fillRect(x, y, width, height);
// update
// add the speed value to x
x += speed;
// if the square is touching the right edge 490
// or the left edge 0, then invert the speed value *= -1
// so that the square moves in the other direction
if(x > 490 || x < 0) {
speed *= -1;
}
console.log('hi');
setTimeout(animate, 33);
}
// call the animate function manually for the first time
animate();