The HTML5 specification introduces many new features, one of the most exciting ones is the canvas element. HTML 5 canvas provides a way to draw graphics through JavaScript, which is simple to use but powerful. Each canvas element has a context (context) (think of as a page on a drawing board) where any shape can be drawn. The browser supports multiple canvas contexts and provides graphical drawing capabilities through different APIs. Most browsers support 2D canvas contexts - including Opera, Firefox, Konqueror and Safari. In addition, some versions of Opera also support 3D canvas, and Firefox can also support 3D canvas through plug-ins.
This article introduces the basics of 2D canvas and how to use basic canvas functions such as lines, shapes, images and text. To understand this article, you'd better understand the basics of JavaScript.
You can click here to download the example code in this article in batches
| The hyperlinks in the examples in this article are all HTML5 web pages. Currently, browsers that support HTML5 include Chrom, FireFox 3.6, etc. IE does not currently support HTML5, which means that you cannot see the hyperlinks in some examples of this page using IE. |
canvas Basics:
The method to create canvas is simple, you just need to add the <canvas> element to the HTML page:
<canvas id=myCanvas width=300 height=150>
Fallback content, in case the browser does not support Canvas.
</canvas>
In order to reference elements in JavaScript, it is best to set the element ID; you also need to set the height and width of canvas.
Once the canvas is created, let's prepare the brush. To draw a graph in a canvas, you need to use JavaScript. First find the canvas element through the getElementById function, and then initialize the context. Various graphics can then be drawn using the context API. The following script draws a rectangle in canvas (click here to view the effect):
// Get a reference to the element.
var elem = document.getElementById('myCanvas');
// Always check for properties and methods, to make sure your code doesn't break
// in other browsers.
if (elem && elem.getContext) {
// Get the 2d context.
// Remember: you can only initialize one context per element.
var context = elem.getContext('2d');
if (context) {
// You are done! Now you can draw your first rectangle.
// You only need to provide the (x,y) coordinates, followed by the width and
// height dimensions.
context.fillRect(0, 0, 150, 100);
}
}
You can place the above code in the head part of the document, or in an external file.
2D context API:
After introducing how to create canvas, let's take a look at the 2D canvas API to see what can be done with these functions.
Basic lines:
The above example shows how easy it is to draw a rectangle.
The fillStyle and strokeStyle properties can be easily set for rectangle filling and lines. The color value is used the same as CSS: hexadecimal number, rgb(), rgba(), and hsla. FillRect can be used to draw a rectangle with fillRect. Use strokeRect to draw rectangles with only borders and no fills. If you want to clear some canvas, you can use clearRect. The parameters of the above three methods are the same: x, y, width, height. The first two parameters set the (x,y) coordinates, and the last two parameters set the height and width of the rectangle. You can use the lineWidth property to change the line thickness. Let's look at the examples using fillRect, strokeRect clearRect and other:
context.fillStyle = '#00f'; // blue
context.strokeStyle = '#f00'; // red
context.lineWidth = 4;
// Draw some rectangles.
context.fillRect (0, 0, 150, 50);
context.strokeRect(0, 60, 150, 50);
context.clearRect (30, 25, 90, 60);
context.strokeRect(30, 25, 90, 60);
This example rendering is shown in the following figure:
path:
Arbitrary shapes can be drawn via the canvas path (path). You can draw the outline first, then draw the border and fill. Creating a custom shape is simple, start drawing with beginPath() and then draw your figure with straight lines, curves, and other graphics. After drawing, call fill and stroke to add fill or set borders. Call closePath() to end custom graphic drawing. Here is an example of drawing a triangle:
// Set the style properties.
context.fillStyle = '#00f';
context.strokeStyle = '#f00';
context.lineWidth = 4;
context.beginPath();
// Start from the top-left point.
context.moveTo(10, 10); // give the (x,y) coordinates
context.lineTo(100, 10);
context.lineTo(10, 100);
context.lineTo(10, 10);
// Done! Now fill the shape, and draw the stroke.
// Note: your shape will not be visible until you call any of the two methods.
context.fill();
context.stroke();
context.closePath();
The renderings are shown in the following figure:
Another more complex example uses straight lines, curves, and arcs.
Insert image:
The drawImage method allows inserting other images (img and canvas elements) in canvas. In Opera, you can draw SVG graphics in canvas. This method is more complicated and can have 3, 5 or 9 parameters
3 parameters: the most basic method of using drawImage. One parameter specifies the image position, and the other two parameters specifies the position of the image in canvas.
5 parameters: Intermediate drawImage usage method, including the 3 parameters mentioned above, add two parameters to indicate the insert image width and height (if you want to change the image size).
9 parameters: The most complex drawImage is a mixed use method, including the above 5 parameters, and the other 4 parameters set the position and height width in the source image. These parameters allow you to dynamically crop the source image before displaying it.
Here are three examples of the above usage methods:
// Three arguments: the element, destination (x,y) coordinates.
context.drawImage(img_elem, dx, dy);
// Five arguments: the element, destination (x,y) coordinates, and destination
// width and height (if you want to resize the source image).
context.drawImage(img_elem, dx, dy, dw, dh);
// Nine arguments: the element, source (x,y) coordinates, source width and
// height (for cropping), destination (x,y) coordinates, and destination width
// and height (resize).
context.drawImage(img_elem, sx, sy, sw, sh, dx, dy, dw, dh);
The effect is shown in the figure below:
Pixel-level operation:
The 2D Context API provides three methods for pixel-level operations: createImageData, getImageData, and putImageData. The ImageData object saves the pixel value of the image. Each object has three properties: width, height, and data. The data attribute type is CanvasPixelArray, which is used to store width*height*4 pixel values. Each pixel has an RGB value and a transparency alpha value (its values are 0 to 255, including alpha!). The order of pixels is stored from left to right, from top to bottom, by row. To better understand its principle, let's look at an example - draw a red rectangle:
// Create an ImageData object.
var imgd = context.createImageData(50,50);
var pix = imgd.data;
// Loop over each pixel and set a transparent red.
for (var i = 0; n = pix.length, i < n; i += 4) {
pix[i] = 255; // red channel
pix[i+3] = 127; // alpha channel
}
// Draw the ImageData object at the given (x,y) coordinates.
context.putImageData(imgd, 0,0);
Note: Not all browsers implement createImageData. In supported browsers, the ImageData object needs to be obtained through the getImageData method. Please refer to the sample code.
ImageData can be used to complete many functions. For example, image filters can be implemented, or mathematical visualizations can be implemented (such as fractals and other special effects). The following special effects implement a simple color inversion filter:
// Get the CanvasPixelArray from the given coordinates and dimensions.
var imgd = context.getImageData(x, y, width, height);
var pix = imgd.data;
// Loop over each pixel and invert the color.
for (var i = 0, n = pix.length; i < n; i += 4) {
pix[i] = 255 - pix[i]; // red
pix[i+1] = 255 - pix[i+1]; // green
pix[i+2] = 255 - pix[i+2]; // blue
// i+3 is alpha (the fourth element)
}
// Draw the ImageData at the given (x,y) coordinates.
context.putImageData(imgd, x, y);
The following figure shows the effect after using this filter:
Word:
Although the recent WebKit version and Firefox 3.1 nightly build have just begun to support the Text API, in order to ensure the integrity of the article, I decided to still introduce the text API here.
The following text properties can be set in the context object:
font: Text font, same as CSSfont-family attribute
textAlign: Text horizontal alignment. Desirable attribute values: start, end, left, right, center. Default value: start.
textBaseline: vertical alignment of text. Desirable attribute values: top, hanging, middle, alphabetic, ideaographic, bottom. Default value: alphabetic
There are two ways to draw text: fillText and strokeText. The first draws text with fillStyle fill, the latter draws text with only the strokeStyle border. The parameters of both are the same: the text to be drawn and the position (x,y) coordinates of the text. There is also an optional option - Maximum Width. If needed, the browser reduces the text to fit the specified width. The text alignment attribute affects the relative position of the text to the set (x,y) coordinates.
Here is an example of drawing hello world text in canvas:
context.fillStyle = '#00f';
context.font = 'italic 30px sans-serif';
context.textBaseline = 'top';
context.fillText ('Hello world!', 0, 0);
context.font = 'bold 30px sans-serif';
context.strokeText('Hello world!', 0, 50);
The following picture is its rendering:
shadow:
Currently only Konqueror and Firefox 3.1 nightly build support the Shadows API. The properties of the API are:
shadowColor: Shadow Color. Its value is consistent with the CSS color value.
shadowBlur: Sets the degree of shadow blur. The larger this value, the more blurry the shadow. Its effect is the same as Photoshop's Gaussian fuzzy filter.
shadowOffsetX and shadowOffsetY: The x and y offsets of the shadow, in pixels.
Here is an example of the canvas shadow:
context.shadowOffsetX = 5;
context.shadowOffsetY = 5;
context.shadowBlur = 4;
context.shadowColor = 'rgba(255, 0, 0, 0.5)';
context.fillStyle = '#00f';
context.fillRect(20, 20, 150, 100);
The effect is shown in the figure below:
Color gradient:
In addition to CSS colors, fillStyle and strokeStyle properties can be set to CanvasGradient objects. -Colour gradients can be used for lines and fills via CanvasGradient. To create a CanvasGradient object, you can use two methods: createLinearGradient and createRadialGradient. The former creates a linear color gradient, and the latter creates a circular color gradient. After creating a color gradient object, you can use the addColorStop method of the object to add color intermediate values. The following code demonstrates how to use color gradients:
// You need to provide the source and destination (x,y) coordinates
// for the gradient (from where it starts and where it ends).
var gradient1 = context.createLinearGradient(sx, sy, dx, dy);
// Now you can add colors in your gradient.
// The first argument tells the position for the color in your gradient. The
// accepted value range is from 0 (gradient start) to 1 (gradient end).
// The second argument tells the color you want, using the CSS color format.
gradient1.addColorStop(0, '#f00'); // red
gradient1.addColorStop(0.5, '#ff0'); // yellow
gradient1.addColorStop(1, '#00f'); // blue
// For the radial gradient you also need to provide source
// and destination circle radius.
// The (x,y) coordinates define the circle center points (start and
// destination).
var gradient2 = context.createRadialGradient(sx, sy, sr, dx, dy, dr);
// Adding colors to a radial gradient is the same as adding colors to linear
// gradients.
I also prepared a more complex example using linear color gradients, shadows, and text.
The effect is shown in the figure below:
canvas demo:
If you want to know what you can do with Canvas, please refer to the following project:
Opera Widget:
SimAquarium
Artist's Sketchbook
Spirograph
Online engineering and demonstration:
Newton polynomial
Canvascape - 3D Walker
Paint.Web - painting demo, open-source
Star-field flight
Interactive blob
Subsection:
Canvas is one of the most anticipated features of HTML 5 and is currently supported by most web browsers. Canvas can help create games and enhance graphical user interfaces. 2D context
The API provides a lot of graphics drawing capabilities - I hope you have learned about using canvas through this article and you are interested in learning more!