HTML5 and CSS3, Second Edition

(singke) #1

Tip 17


Tip 17. Drawing a Logo on the Canvas


Let’s begin our exploration of the HTML5 canvas by learning how to draw
simple shapes and lines. Before we can draw anything, we have to add the
<canvas> tag to our page. The <canvas> tag doesn’t do anything by itself. Adding
one to our page gives us a blank slate we can draw on using JavaScript code.
We define a canvas with a width and height like this:

html5_canvas/canvas_simple_drawing.html
<canvasid="my_canvas"width="150" height="150">
Fallbackcontenthere
</canvas>

Unfortunately, you can’t use CSS to control or alter the width and height of
a <canvas> element without distorting the contents, so you need to decide on
your canvas dimensions when you declare it, or you need to adjust everything
programatically.

We use JavaScript to put shapes on the canvas. Even if we provided fallback
content to browsers that don’t support the <canvas> tag, we still need to prevent
the JavaScript code from trying to manipulate it. The best way to do that is
to run our JavaScript only when the browser supports <canvas>. Here’s how:

html5_canvas/canvas_simple_drawing.html
varcanvas= document.getElementById('my_canvas');
if(canvas.getContext){
varcontext= canvas.getContext('2d');

}else{
// do somethingto showthe canvas'shiddencontents
// or let the browserdisplaythe text withinthe <canvas>element.
}

We locate the <canvas> element by its id and then we call the getContext() method.
If we get a response from the getContext() method, we grab the 2D context for
the canvas so we can add objects. If we don’t have a context, we don’t want
to run any code. We’re building a framework to handle fallbacks from the
beginning, because unlike in other situations, our users will see JavaScript
errors if we try to access the context on browsers that don’t support it.

Chapter 6. Drawing in the Browser • 112


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

Free download pdf