O'Reilly logo

Supercharged JavaScript Graphics by Raffaele Cecco

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

Canvas Drawing Basics

The basic Canvas drawing commands are straightforward to implement and are discussed in the following sections.

The Canvas Element

Inserting a Canvas element into a web page is no different than inserting any other HTML element:

<canvas id = 'mycanvas' width = 512 height = 384>
    Fallback content
</canvas>

If you don’t specify any width or height attributes, the default size will be 300 × 150 pixels. It is possible to change the canvas size via CSS (e.g., width:50%), but it’s not recommended; depending on the browser implementation, the output may become distorted or scaled. However, you can style the element with the usual borders, margins, and background colors, although this in no way affects drawing to the canvas itself. The coordinate system has its default origin in the top left—coordinate (0,0)—so, for example, something drawn at coordinate (10, 15) would be positioned 10 pixels from the left and 15 pixels from the top.

If Canvas is not available to the browser, the fallback content between the start and end tags is displayed. Ideally, this should be the regular text or HTML representation of the data that was to be displayed by Canvas. For example, where Canvas might have displayed a pie chart, the fallback content would display a regular table. There are situations where fallback content simply cannot replace Canvas; games and drawing applications don’t have non-Canvas equivalents. In these cases, the fallback content should display a useful message explaining ...

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