<!DOCTYPE html>
<html>
<head>
<title>Script-based animation using requestAnimationFrame</title>
<style type="text/css">
canvas {
border: 1px solid black;
}
</style>
</head>
<body onload="init();">
<canvas id="myCanvas" width="400" height="400">
Your browser does not support the canvas tag.
</canvas>
<p>
<button onclick="start()">Start animation</button>
<button onclick="stop()">Stop animation</button>
<script>
var canvas, ctx;
var monsterX = 100,
monsterY = 100,
monsterAngle = 0;
function init() {
// This function is called after the page is loaded
// 1 - Get the canvas
canvas = document.getElementById('myCanvas');
// 2 - Get the context
ctx = canvas.getContext('2d');
}
function animationLoop(timestamp) {
// 1 - Clear
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 2 Draw
drawMonster(monsterX, monsterY, monsterAngle, 'green', 'yellow');
// 3 Move
monsterX += 10;
monsterX %= canvas.width
monsterAngle += 0.01;
// call again mainloop after 16.6 ms (60 frames/s)
requestId = requestAnimationFrame(animationLoop);
}
function drawMonster(x, y, angle, headColor, eyeColor) {
// GOOD PRACTICE : SAVE CONTEXT AND RESTORE IT AT THE END
ctx.save();
// Moves the coordinate system so that the monster is drawn
// at position (x, y)
ctx.translate(x, y);
ctx.rotate(angle)
// head
ctx.fillStyle = headColor;
ctx.fillRect(0, 0, 200, 200);
// eyes
ctx.fillStyle = 'red';
ctx.fillRect(35, 30, 20, 20);
ctx.fillRect(140, 30, 20, 20);
// interior of eye
ctx.fillStyle = eyeColor;
ctx.fillRect(43, 37, 10, 10);
ctx.fillRect(143, 37, 10, 10);
// Nose
ctx.fillStyle = 'black';
ctx.fillRect(90, 70, 20, 80);
// Mouth
ctx.fillStyle = 'purple';
ctx.fillRect(60, 165, 80, 20);
// GOOD PRACTICE !
ctx.restore();
}
function start() {
// Start the animation loop, targets 60 frames/s
requestId = requestAnimationFrame(animationLoop);
}
function stop() {
if (requestId) {
cancelAnimationFrame(requestId);
}
}
</script>
</body>
</html>
Comments