O'Reilly logo

Learning PHP, MySQL & JavaScript, 5th Edition by Robin Nixon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 24. 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 by 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 20 (in the file OSC.js) to 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 Chapter 23, I showed you how to draw a simple circle to display the Japanese flag, as in Example 24-1. Let’s now look at what exactly is going on here.

Example 24-1. Displaying the Japanese flag by 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> ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required