HTML5 and CSS3, Second Edition

(singke) #1
We can create complex images on the canvas by combining simple shapes,
lines, arcs, and text. Let’s do a more complex example by re-creating the
AwesomeCo logo using the canvas. The logo is pretty simple, as the following
figure shows.

Figure 17—The AwesomeCo logo


The logo consists of a string of text, an angled path, a square, and a triangle.
Let’s start by creating a new HTML5 document for this logo. We’ll do everything
in the same file for simplicity. We’ll add a <script> block right above the closing
<body> tag, which will hold our code for creating the logo.

html5_canvas/logo.html
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="utf-8">
<title>AwesomeCoLogoTest</title>
</head>
<body>
<script>
</script>
</body>
</html>

We’ll start our JavaScript by creating a JavaScript function for drawing the
logo, which detects whether we can use the 2D canvas.

html5_canvas/logo.html
vardrawLogo=function(){
varcanvas= document.getElementById("logo");
varcontext= canvas.getContext("2d");
};

We invoke this method after first checking for the existence of the <canvas>
element, like this:

html5_canvas/logo.html
varcanvas= document.getElementById("logo");

if(canvas.getContext){
drawLogo();
}

Chapter 6. Drawing in the Browser • 114


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf