<canvas> is a new html element that can be used by script language (usually JavaScript) to draw graphics. For example, it can be used to draw pictures, synthesize images, or do simple (and not so simple) animations. The image on the right shows some application examples of <canvas>, and we will see their implementation in this tutorial.
<canvas> was first introduced on Apple's mac os x dashboard and then applied to safari. Browsers based on gecko1.8, such as firefox 1.5, also support this new element. The element <canvas> is part of whatwg web applications 1.0, which is known to everyone, the HTML 5 standard specification.
In this tutorial, I'll try to tell you how to use the <canvas> element in your own web page. The examples provided should give you some clear concepts, namely what you can do with <canvas>. These examples can also serve as a starting point for your application <canvas>.
Before you start using
Using the element <canvas> is not difficult, as long as you have the basic knowledge of html and javascript.
As mentioned above, not all modern browsers support <canvas> elements, so you need firefox 1.5 or later, or other gecko-based browsers such as Opera 9, or a recent version of safari to see all examples' actions.
<canvas> element
let's start this tutorial by looking at the <canvas> element itself.
Let's start with the definition of the <canvas> element.
<canvas id=tutorial width=150 height=150></canvas>
This looks a lot like the <img> element, the only difference is that it doesn't have the src and alt attributes. <canvas> looks a lot like the <img>, the only difference is that it doesn't have the src and alt attributes. the <canvas> element has only two attributes - width and height . these are both optional and can also be set using dom properties or css rules. When no width and height attributes are specified, the canvas will initially be 300 pixels wide and 150 pixels high . The element can be sized arbitrarily by css, but during rendering the image is scaled to fit its layout size. (if your renderings seem distorted, try specifying your width and height attributes explicitly in the <canvas> attributes, and not with css.) Although the size of the canvas can be resized through css, the rendering image will scale to adapt to the layout (if you find that the rendering results look deformed, you don't have to rely on css, you can try to explicitly specify the width and height attribute values of the canvas).
the id attribute isn't specific to the <canvas> element but is one of default html attributes which can be applied to (almost) every html element (like class for instance). it's always a good idea to supply an id because this makes it much easier to identify it in our script.
The id attribute is not exclusive to <canvas>. Just like the standard html tag, any html element can specify its id value. Generally, it is a good idea to specify an id for an element, which makes it easier to apply in scripts.
the <canvas> element can be styled just like any normal image (margin, border, background, etc). these rules however don't affect the actual drawing on the canvas. we'll see how this is done later in this tutorial. when no styling rules are applied to the canvas it will initially be fully transparent. The <canvas> element can be styled just like any normal image (margin, border, background, etc). these rules however don't affect the actual drawing on the canvas. we'll see how this is done later in this tutorial. when no styling rules are applied to the canvas it will initially be fully transparent. The <canvas> element can be styled just like any normal image (margin, border, background, etc.) is as if it were a normal image. However, these styles do not have any effect on the actual image generated by canvas. Below we will see how to apply styles. If you do not specify a style, canvas is completely transparent by default.
Because the <canvas> element is still relatively new and isn't implemented in some browsers (such as firefox 1.0 and internet explorer), we need a means of providing fallback content when a browser doesn't support the element.
Because <canvas> is relatively new, some browsers do not implement it, such as firefox 1.0 and internet explorer, we need to provide alternative display content for browsers that do not support canvas.
luckyily this is very straightforward: we just provide alternative content inside the canvas element. browsers who don't support it will ignore the element completely and render the fallback content, others will just render the canvas normally.
for instance we could provide a text description of the canvas content or provide a static image of the dynamically rendered content. this can look something like this:
We just need to insert substitute content directly into the canvas element. Browsers that do not support canvas will ignore the canvas elements and directly render the alternative content, while supported browsers will render canvas normally. For example, we can fill in some text or pictures into canvas as alternative content:
<canvas id=stockgraph width=150 height=150> current stock price: $3.15 +0.15</canvas><canvas id=clock width=150 height=150> <img src=images/clock.png width=150 height=150/></canvas>
in the apple safari implementation, <canvas> is an element implemented in much the same way <img> is; it does not have an end tag. however, for <canvas> to have widespread use on the web, some facility for fallback content must be provided. therefore, mozilla's implementation requires an end tag (</canvas>).
In apple safari, the implementation of <canvas> is very similar to <img>, and it does not have an end tag. However, in order for <canvas> to be widely applicable in the web world, it is necessary to provide a place for alternative content, so ending the tag (</canvas>) in the implementation of mozilla is necessary.
if fallback content is not needed, a simple <canvas id=foo ...></canvas> will be fully compatible with both safari and mozilla -- safari will simply ignore the end tag.
If there is no substitute, <canvas id=foo ...></canvas> is fully compatible with safari and mozilla - safari simply ignores the end tag.
If fallback content is desired, some css tricks must be employed to mask the fallback content from safari (which should render just the canvas), and also to mask the css tricks themselves from ie (which should render the fallback content).
If there is alternative content, you can use some css tricks to hide alternative content for and only for safari, because those alternative content needs to be displayed in ie but not in safari.
<canvas> creates a fixed size drawing surface that exposes one or more rendering contexts , which are used to create and manipulate the content shown. we'll focus on the 2d rendering context, which is the only currently defined rendering context. in the future, other contexts may provide different types of rendering; for example, it is likely that a 3d context based on opengl es will be added.
The fixed-size drawing screen created by <canvas> opens up one or more rendering contexts, through which we can control what to display. We focus on 2D rendering, which is also the only option at present, and may add 3D context based on opengl es in the future.
the <canvas> is initially blank, and to display something a script first needs to access the rendering context and draw on it. the canvas element has a dom method called getcontext, used to obtain the rendering context and its drawing functions. getcontext() takes one parameter, the type of context.
The initialization of <canvas> is blank. To draw a script on it, it first requires its rendering context. It can be obtained through the getcontext method of the canvas element object. At the same time, some functions are obtained for drawing. getcontext() accepts a value that describes its type as an argument.
var canvas = document.getelementbyid('tutorial');var ctx = canvas.getcontext('2d');in the first line we retrieve the canvas dom node using the getlementbyid method. we can then access the drawing context using the getcontext method.
The first line above obtains the dom node of the canvas object through the getelementbyid method. Then, the drawing operation context is obtained through its getcontext method.
the fallback content is displayed in browsers which do not support <canvas>; scripts can also check for support when they execute. this can easily be done by testing for the getcontext method. our code snippet from above becomes something like this:
In addition to displaying alternative content on unsupported browsers, you can also check whether the browser supports canvas through scripts. The method is very simple, just judge whether the getcontext exists.
var canvas = document.getelementbyid('tutorial');if (canvas.getcontext){ var ctx = canvas.getcontext('2d'); // drawing code here} else { // canvas-unsupported code here}Here is a minimalistic template, which we'll be using as a starting point for later examples. you can download this file to work with on your system.
We will start with the following simplest code template (required for subsequent examples), and you can download the file to be used locally.
<html> <head> <title>canvas tutorial</title> <script type=text/javascript> function draw(){ var canvas = document.getelementbyid('tutorial'); if (canvas.getcontext){ var ctx = canvas.getcontext('2d'); } } </script> <style type=text/css> canvas { border: 1px solid black; } </style> </head> <body onload=draw();> <canvas id=tutorial width=150 height=150></canvas> </body></html>If you look at the script you'll see i've made a function called draw, which will get executed once the page finishes loading (via the onload attribute on the body tag). this function could also have been called from a settimeout, setinterval, or any other event handler function just as long the page has been loaded first.
If you are careful, you will find that I have prepared a function called draw, which will be executed once after the page is loaded (by setting the onload property of the body tag), and of course it can also be called in settimeout, setinterval, or other event handling functions.
to start off, here's a simple example that draws two intersecting rectangles, one of which has alpha transparency. we'll explore how this works in more details in later examples.
To start, let's take a simple look - draw two interlaced rectangles, one of which has an alpha transparent effect. We will give you a detailed look at how it works in the following example.
<html> <head> <script type=application/x-javascript> function draw() { var canvas = document.getelementbyid(canvas); if (canvas.getcontext) { var ctx = canvas.getcontext(2d); ctx.fillstyle = rgb(200,0,0); ctx.fillrect (10, 10, 55, 50); ctx.fillstyle = rgba(0, 0, 200, 0.5); ctx.fillrect (30, 30, 55, 50); } } </script> </head> <body onload=draw();> <canvas id=canvas width=150 height=150></canvas> </body></html>