Chapter 23. The HTML5 Canvas

Although the collective term given to the new web technologies is HTML5, they are not all simply HTML tags and properties. Such is the case with the canvas element. Yes, you create a canvas using the <canvas> tag, and maybe supply a width and height, and can modify it a little with CSS, but to actually write to (or read from) a canvas, you must use JavaScript.

Thankfully, the JavaScript you need to learn is minimal and very easy to implement, plus I’ve already provided you with a set of three ready-made functions in Chapter 21 (in the file OSC.js) that make accessing objects such as the canvas even more straightforward. So let’s dive right in and start using the new <canvas> tag.

Creating and Accessing a Canvas

In the previous chapter, I showed you how to draw a simple circle to display the Japanese flag, as in Example 23-1. Let’s now look at what exactly is going on.

Example 23-1. Displaying the Japanese flag using a canvas
<!DOCTYPE html> <html> <head> <title>The HTML5 Canvas</title> <script src='OSC.js'></script> </head> <body> <canvas id='mycanvas' width='320' height='240'> This is a canvas element given the ID <i>mycanvas</i> This text is only visible in non-HTML5 browsers </canvas> <script> canvas = O('mycanvas') context = canvas.getContext('2d') context.fillStyle = 'red' S(canvas).border = '1px solid black' context.beginPath() context.moveTo(160, 120) context.arc(160, 120, 70, 0, Math.PI * 2, false) context.closePath() context.fill() </script> </body> ...

Get Learning PHP, MySQL, JavaScript, CSS & HTML5, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.