This week I finally had the chance to start looking at this book I bought a few months ago, it’s called The essential guide to HTML5. The book is based on a bunch of exercises (games really) using JavaScript and HTML5 Canvas, ready to put into code and test. It doesn’t get into theory but for those looking to get things working quickly, this is definitely a good one.
So I decided to make the “Memory Game” to learn about the basics of canvas:
So, what is canvas? and what you can do with it?
<canvas> is a HTML5 element used to draw graphics using JavaScript (most of the times). Imagine a blank paper where you can draw shapes, images and text. When adding it to your page it exposes one or more rendering contexts which are used to create and manipulate the content that will be displayed. The demo uses the 2d context.
Canvas are mostly used for creating graphics, animations, games and images compositions.
The basic code for using and initialising a canvas will look like this:
HTML code
Sorry, your browser doesn't support the HTML5 element canvas.
</canvas>
The id wil be used to initialise the canvas using JavaScript, the width and height to set the size of it and the text inside will be used as a callback when the browser doesn’t support it (check this useful link to see the list of browsers and versions that support canvas).
JavaScript code
// check if browser supports it
if (canvas && canvas.getContext) {
ctx = canvas.getContext('2d');
if (ctx) {
// Start drawing here
}
}
Start drawing!
If you want to learn more about canvas check out this link. It’s from the Mozilla developer’s website and it helped me a lot with the theory behind canvas and all the things you can create. As you will see, there is a lot of possibilities and all depends in what you want to achieve.
Check out the demo
To see the memory card demo click here and its javaScript code here. Bear on mind this is a basic example only for practice purposes =)









