Click here to play (Chrome, Firefox)
This is a little game, that I wrote to become acquainted with some new Web technologies like
Canvas and Embeddable Fonts
My son once brought home a little paper toy top (german: ‘Kreisel’) lately, that had a simple, but interesting geometric shape. It looks like that:
Thinking about that shape, it was clear, that I could very well do that with a Canvas in Javascript. Ok, this one was quite simple:
var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d");
var colors = [
['blue', 'yellow'],
['white', 'pink'],
['green', 'red'],
['white', 'black'],
['green', 'blue'],
['red', 'green', 'blue']
];
for (var i = 0; i < 12; i++) {
for (var cIdx = 0, p = 0; p < 120; p += 20, cIdx++) {
var cols = colors[cIdx];
for (var r = p; r < p + 20; r++) {
ctx.beginPath();
ctx.arc(125, 125, r, (i - 1) * Math.PI / 6.0, i * Math.PI / 6.0);
ctx.strokeStyle = cols[i % cols.length];
ctx.stroke();
}
}
}
Ok, so if we have a Toy Top, it needs to move. This isn’t overly complicated.
I just have to look, in which directions it moves and in which direction
it rotates. For rotating, I’m using CSS () to rotate the whole HTML5 Canvas.
How do I determine, how my object moves?
$("canvas").mousedown(function(e) {
dragX = e.pageX;
dragY = e.pageY;
nowT = window.performance.now();
});
$("canvas").mouseup(function(e) {
dragDeltaX = e.pageX - dragX;
dragDeltaY = e.pageY - dragY;
deltaT = parseInt(window.performance.now() - nowT);
deltaX = dragDeltaX / deltaT;
deltaY = dragDeltaY / deltaT;
rotate(deltaX, deltaY); // animate the object now
});
As you can see, there are three deltas (for X/Y direction and one for the
time between the mousedown and the mouseup event).
Animating the toy top is trivial. It’s just updating the X and Y positions
of the Canvas (containing the toy top) for a certain number of times every
1/10s.
Now moving to the embeddable fonts. That’s a wonderful thing in HTML5:
You can use any TTF directly on your page. Just do that in CSS:
@font-face {
font-family: "crayonFont";
src: url("../images/PastelCrayon.ttf") format("truetype");
}
What’s the aim of the game?
Just move the toy top into the green circles, that appear randomly on the playfield.
Catch 5 circles within 90s and you win! Don’t fall off the playfield, don’t be slow.
Have fun (for 5 minutes 😉 ).