5 The specification introduces many new features, one of the most exciting ones is canvas element. html5 canvas provides a way to draw graphs through javascript, which is simple to use but powerful. Each canvas element has a context (context) (think of as a page on the drawing board) where any shape can be drawn. The browser supports multiple canvas contexts and provides graphical drawing functions through different ones. Provides graphic drawing function. 5 The specification introduces many new features, one of the most exciting ones is the elements. html5 provides a method for drawing graphics through javascript, which is simple to use but powerful. Each 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 functions through different ones.
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:
Context article
This article introduces 2d canvas
Basics 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 method to create canvas is very 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 be able to reference elements in javascript, it is best to set the id for the element; it also needs to set the height and width for 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 canvas through getelementbyid function
element, then initialize the context. Various graphics can be drawn later 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 和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 head part of the document, or in an external file.
After introducing how to create canvas, let's take a look at the 2d canvas API and see what can be done with these functions.
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. Color value usage method and hexadecimal number, (), () and () (if the browser supports it, such as opera
10 and firefox 3). () (If the browser supports it, such as opera10 and firefox 3). () and () (if the browser supports it, such as opera10 and firefox 3). (), () and () (if the browser supports it, such as opera10 and firefox 3). Hexadecimal numbers, (), () and () (if supported by the browser, such as opera10 and firefox 3).
fillrect can be used to draw a fill-in rectangle. 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 attribute to change the line thickness. Let's see if fillrect is used,
strokerect clearrect and other examples:
context.fillstyle = '#00f'; // bluecontext.strokestyle = '#f00'; // redcontext.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 Figure 1.
Figure 1: fillrect, strokerect and
clearrect effect diagram
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) coordinatescontext.lineto(100, 10);context.lineto(10, 100);context.lineto(10, 10);// done! now fill the shape, 和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 Figure 2.
Figure 2: Triangle
Another more responsible example uses straight lines, curves and arcs.
The drawimage method allows inserting other images in canvas
( img and canvas elements). In operator, you can draw svg graphics in canvas. This method is quite complex and can have 3, 5 or 9 parameters:
drawimage . One parameter specifies the image position, and the other two parameters specifies the position of the image in canvas.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).drawimage usage 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 Figure 3.
Figure 3: drawimage rendering.
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 value is 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 - drawing a red rectangle
// create an imagedata object.var imgd = context.createimagedata(50,50);var pix = imgd.data;// loop over each pixel 和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, imagedata object needs to be obtained through getimagedata method. Please refer to the sample code.
Many functions can be accomplished through imagedata . 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 );Figure 4 shows the Opera after using this filter
Image (Figure 3 is the original image).
Figure 4: Color inversion filter
Although the recent webkit version and firefox 3.1 nightly build have only started to support text APIs, 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 context object:
font : text font, same font-family attribute 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 , ideographic , 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 stroke style 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.
Text alignment attribute affects text and settings
(x,y) The relative position of the 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);Figure 5 is its rendering.
Figure 5: Text effect
Currently only konqueror and firefox 3.1 nightly build support 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 the Gaussian fuzzy filter in photoshop.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 Figure 6.
Figure 6: Canvas Shadow Effect - Blue Rectangle, Red Shadow
In addition to css color, fillstyle and strokestyle properties can be set to canvasgradient objects. - canvasgradient can use color gradients for lines and fills.
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 和destination (x,y) coordinates // for the gradient (from where it starts 和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'); // redgradient1.addcolorstop(0.5, '#ff0'); // yellowgradient1.addcolorstop(1, '#00f'); // blue// for the radial gradient you also need to provide source// 和destination circle radius.// the (x,y) coordinates define the circle center points (start 和// 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 Figure 7.
Figure 7: Example of using linear color gradient
If you want to know what you can do with canvas, please refer to the following project:
sketchbook
demo, open-source
flight
canvas is one of the most anticipated features of html5 and has been supported by most web browsers. canvas can help create games and enhance graphical user interfaces. 2d context
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!