When you use a canvas element in your web page, it creates a rectangular
area on the page. By default, this rectangular area is 300 pixels wide and 150
pixels high, but you can specify the exact size and set other attributes for
your canvas element. A basic canvas element:
<canvas> </canvas>
Once you have added a canvas element to your page, you can use JavaScript to manipulate it any way you want. You can add graphics, lines, and text to it; you can draw on it; and you can even add advanced animations to it.
The HTML5 Canvas API supports the same two-dimensional drawing operations that most modern operating systems and frameworks support. If you have ever programmed two-dimensional graphics in recent years, you will probably feel right at home with the HTML5 Canvas API because it is designed to be similar to existing systems. If you haven’t, you’re about to discover how much more powerful a rendering system can be than the previous images and CSS tricks developers have used for years to create web graphics.
To programmatically use a canvas, you have to first get its context. You can then perform actions on the context and finally apply those actions to the context. You can think of making canvas modifications as similar to database transactions: you start a transaction, perform certain actions, and then commit the transaction.
When Not to
Use Canvas
Although the canvas element is great and very useful, you should not use
the canvas element when another element will suffice. For example, it would not
be a good idea to dynamically draw all the different headings for an HTML document
on a canvas instead of simply using heading styles (H1, H2, and so on) that are
meant for that purpose.
CSS and
Canvas
As with most HTML elements, CSS can be applied to the canvas element
itself to add borders, padding, margins, etc. Additionally, some CSS values are
inherited by the contents of the canvas; fonts are a good example, as fonts
drawn into a canvas default to the settings of the canvas element itself. Furthermore,
properties set on the context used in canvas operations follow the syntax you
may already be familiar with from CSS. Colors and fonts, for example, use the
same notation on the context that they use throughout any HTML or CSS document.
Adding a
Canvas to a Page
Adding a canvas element in an HTML page is pretty straight-forward.
The canvas element:
<canvas height="300" width="300"></canvas>
The resulting canvas will show up as an “invisible” 300 × 300 pixel rectangle on your page. If you want to add a border around it.
No comments:
Post a Comment