Yan Cui
I help clients go faster for less using serverless technologies.
This article is brought to you by
I never fully recovered my workspace setup when I upgraded my laptop two years ago, and I still miss things today. If only I had known about Gitpod back then…
One of the cool new features introduced by HTML5 is the new <canvas> tag, which defines an area for you to draw graphics on using javascript.
Basics
To create a canvas element is as easy as inserting a <canvas> tag like this:
<canvas id="myCanvas" width="400" height="400"></canvas>
Typically you will give it an ID as you will need to look it up with javascript later in order to do anything with it, and as for the javascript, pretty much all javascript that interacts with the canvas need to start with something along the line of:
// get the element by ID var element = document.getElementById("myCanvas"); // get the 2D context which is what you use to draw var context = element.getContext("2d");
To make this more robust you’re likely to need more plumbing code to check whether the browser supports the <canvas> tag and if element is not null and that the getContext method exists, etc. The easiest way to check for browser support for the <canvas> tag would be to use a simple library like Modernizr, and all you need is to check the .canvas property:
<script type="text/javascript" src="modernizr/modernizr-1.6.min.js"></script> … $(document).ready(function () { // check if canvas is not supported if (!Modernizr.canvas) { // fall back logic here } else { // normal steps here } });
Once you’ve got the 2D context (specification for a 3D context is in the pipeline and some vendors have released their own 3D context API) you can use it to draw paths, shapes, text, etc. etc.
API
Seeing as all the action around a canvas element is centred around the 2D context, it’s only fitting that it gets its own specification. The full specification (work in progress of course) of the 2D context object can be found here.
Have a look at the links in the References section for some useful articles which go through the various API calls you’ll likely need to use in detail.
Resetting a canvas
Setting the width or height of the canvas element will erase its contents and reset all the properties of its drawing context to their default, so something like this will suffice:
var canvas = $("#myCanvas"); canvas.width = canvas.width;
Demo
Once you’ve had a chance to look at the basic API methods, I’ve put together a quick example here to demonstrate how to draw some basic gradients using two stop and how to draw a chessboard using the fillRec and strokeRect methods:
// draws a chessboard
function drawChessboard() {
// define the constants
var baseX = 0.5, baseY = 0.5, width = 50;
// get the 2D context from the “chessboard” canvas
var context = document.getElementById(“chessboardCanvas”).getContext(“2d”);
// draws the 8 by 8 chessboard
for (var i = 0; i < 8; i++) {
for (var j = 0; j < 8; j++) {
var x = baseX + width * i, y = baseY + width * j;
// draw the rectangle
context.strokeRect(x, y, width, width);
// fill the odd number rectangles
if ((i + j) % 2 != 0) {
context.fillRect(x, y, width, width);
}
}
}
}
[/code]
The baseX and baseY are set to 0.5 for the reason explained in the Dive into HTML5 article (see reference), that if you draw a one pixel wide line between whole number coordinates you will end up with a two pixels wide line instead.
The rest is fairly straight forward and draws a 8×8 chessboard of alternating empty and filled squares, left to right, top to bottom, with the first square being unfilled.
References:
Mozilla Developer Center’s canvas tutorial
Related posts:
Having fun with HTML5 – Canvas, part 2
Having fun with HTML5 – Canvas, part 3
Having fun with HTML5 – Canvas, part 4
Having fun with HTML5 – Canvas, part 5
Whenever you’re ready, here are 3 ways I can help you:
- Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
- I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
- Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.
Pingback: Having fun with HTML5 – Canvas, Part 2 | theburningmonk.com
Pingback: Having fun with HTML5 – Canvas, part 3 | theburningmonk.com
Pingback: Having fun with HTML5 – Canvas, part 5 | theburningmonk.com
Hi
Thanks for this canvas article.
I have played around with the chessboard example but have a problem with it.
I made the canvas area larger & want to position the chessboard in the canvas div but it ‘sticks’ to the top left corner of the canvas div area no matter what I do!
How can I reposition this board? Most grateful for advice -many thanks
Hi Richard,
Do you have your code somewhere so I can take a look and see what’s wrong with it? If you don’t want to make it publicly available, feel free to email it to me instead at theburningmonk@gmail.com.
So changing the ‘baseX’ and ‘baseY’ values have no effect on the position of the chessboard inside the canvas div?
Hi tbm
Thanks for your prompt & helpful reply which has fixed the problem for me.
I obviously did not understand var BaseX 0.5 & BaseY 0.5.
Simply changing baseX & baseY values to the coordinates I want then positions the chessboard appropriately as you advised. A 2 pixel border width is not a problem for me here.
Many thanks.
As an aside I now want to add board coordinates around the edge of the board & cannot yet find a method to do this! I would be very grateful for your suggestion (ie 1-8 along side y axis/a-h below x axis). I tried adding divs to canvas element with no success..
Hi Richard,
Try increasing the baseX and baseY values to allow sufficient space on the top and left of your chessboard and then work out where the coordinates should be shown and then use context.fillText to draw the coordinates.
Have a look at some examples here: http://diveintohtml5.info/canvas.html