Canvas Animation
by Anton
HTML
<canvas width="300" height="300" />
CSS
canvas {
border: solid 2px #777;
}
JavaScript
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const width = canvas.getAttribute('width');
const height = canvas.getAttribute('height');
let hero, prize;
const delta = 3;
class Item {
constructor(isHero = false) {
this.isHero = isHero;
this.x = 0;
this.y = 0;
this.size = 30;
this.points = 0;
this.flashTimer = 0;
}
draw() {
if(this.flashTimer > 0) {
ctx.fillStyle = '#ffffb0';
this.flashTimer--;
} else {
ctx.fillStyle = this.isHero ? '#e00' : '#080';
}
ctx.fillRect(this.x, this.y, this.size, this.size);
if(this.isHero) {
ctx.font = '10pt Verdana';
ctx.fillStyle = '#fff';
ctx.fillText(this.points, this.x + 1, this.y + this.size - 2);
}
}
move(dx, dy) {
this.x += dx;
this.y += dy;
if(this.x > width - this.size) this.x = width - this.size;
if(this.x < 0) this.x = 0;
if(this.y > height - this.size) this.y = height - this.size;
if(this.y < 0) this.y = 0;
}
checkPrize(prize) {
let isPickedUp = this.x + this.size >= prize.x
&& this.x <= prize.x + prize.size
&& this.y + this.size >= prize.y
&& this.y <= prize.y + prize.size;
if(isPickedUp) {
this.points++;
this.flashTimer = 10;
}
return isPickedUp;
}
}
main();
// --------------------------------
function main() {
hero = new Item(true);
nextPrize();
window.requestAnimationFrame(nextFrame);
document.addEventListener('keydown', e => {
switch(e.keyCode) {
case 38: // up
hero.move(0, -delta);
break;
case 39: // right
hero.move(delta, 0);
break;
case 40: // down
hero.move(0, delta);
break;
case 37: // left
hero.move(-delta, 0);
break;
}
});
}
function cls() {
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, width, height);
}
function nextFrame(timestamp) {
if(hero.checkPrize(prize)) {
nextPrize();
}
cls();
...