The following code make a square move left to right, back and forth:
[CODE]<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body onLoad=”animate()”>
<canvas id=”canvas” width=”800″ height=”800″></canvas>
<script>
var canvas = document.getElementById(‘canvas’);
var context = canvas.getContext(‘2d’);
var X = 0;
var Y = 10;
var goRight = true;
var Draw = {
rectangle: function (x, y) {
context.beginPath();
context.rect(x, y, 10, 10);
context.fillStyle = ‘#8ED6FF’;
context.fill();
context.lineWidth = 5;
context.strokeStyle = ‘black’;
context.stroke();
}
}
function animate() {
if (X < 800 && goRight) {
X += 10;
} else if (X > 0 || !goRight) {
X -= 10;
goRight = (X <= 0); // reset direction once we hit 0;
}
context.clearRect(0, 0, canvas.width, canvas.height);
Draw.rectangle(X, Y);
window.requestAnimationFrame(animate);
}
</script>
<button onclick=”animate()”>test</button>
</body>
</html>
However, when I remove the ‘onLoad’ attribute from the body element, I thought that clicking the ‘Test’ button should make the rectangle animate in the same way, but nothing happens. Why is this?