Chapter 26. 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 21 (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 25, I showed you how to draw a simple circle to display the Japanese flag, as reused here in Example 26-1. Letâs now look at what exactly is going on here.
Example 26-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 ...
Get Learning PHP, MySQL & JavaScript, 6th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.