Comments: The HTML 5 specification introduces many new features. One of the most anticipated features is the canvas Element.HTML5 canvas-basic syntax
5. The specification introduces many new features, one of the most promising elements.HTML5. You can use JavaScript to draw images. This method is simple but powerful. Each element has a "context" (as a page on the drawing board) where any image can be drawn. The browser supports multiple canvas contexts and provides different graphic rendering functions.5. The specification introduces many new features, one of the most promising elements. 5. You can use JavaScript to draw images. This method is simple but powerful. Each element has a "context" (as a page on the drawing board) where any image can be drawn. The browser supports multiple canvas contexts and provides different graphic rendering functions.
Most browsers support 2D canvas context, including Opera, Firefox, Konqueror, and Safari. In addition, some versions of Opera also support 3D canvas, and Firefox also supports 3D canvas through plug-ins:
- 3D canvas is supported for downloading,HTMLOpera for video and File I/O
- Article on Opera 3D canvas Context
- About Firefox 3D canvas
Context article
This article introduces 2D canvas
Basic 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 batch download the instance code of this Article
Canvas Basics
The canvas creation method is simple.HTMLAdd<canvas>
Element:
<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 ID for the element. You also need to set the height and width for the canvas.
After creating the canvas, let's prepare the paint brush. JavaScript is required to draw a graph in the canvas. First pass getElementById
The function finds the canvas.
And then initialize the context. Then you can use the context API to draw various images. The following script draws a rectangle in the 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 documenthead
Or put it in an external file.
2D context API
After introducing how to create a canvas, let's take a look at the 2D canvas API to see what can be done with these functions.
Basic Line
The above example shows how easy it is to draw a rectangle.
PassFillStyleAndStrokeStyleYou can easily set the filling and line of a rectangle. Color value usage method and hexadecimal number, (), (), and () (if supported by the browser, such as Opera10 and Firefox 3 ).Hexadecimal number, (), (), and () (if supported by the browser, such as Opera10 and Firefox 3 ).
PassfillRect
You can draw a rectangle with padding. UsestrokeRect
You can draw a rectangle without borders. You can useclearRect
. The parameters of the preceding three methods are the same:X,Y,Width,Height. The first two parameters set the coordinates (x, y), and the last two parameters set the height and width of the rectangle.
AvailableLineWidthProperty to change the line width. Let's take a look.fillRect
,
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 is shown in Figure 1.
Figure 1: fillRect, strokeRect, and
ClearRect
Path
You can draw any shape using the canvas path. You can draw an outline first, then draw a border and fill it. It is easy to create a custom shape. beginPath()
Start drawing, and then draw your graph using straight lines, curves, and other figures. Called after drawingfill
Andstroke
To add or set the border. Call closePath()
End custom image painting.
The following is an example of creating 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, 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 ();
See figure 2.
Figure 2: Triangle
In another example, we use straight lines, curves, and arcs.
Insert Image
drawImage
This method allows you to insert other images into the canvas.
( img
Andcanvas
Element ). In Opera, you can draw SVG images in canvas. This method is complex and can have three, five, or nine parameters:
- Three parameters: the most basic
drawImage
Usage. One parameter specifies the image position, and the other two parameters set the position of the image in the canvas.
- Five parameters: Intermediate
drawImage
The usage includes the three parameters described above. Add two parameters to specify the width and height of the inserted image (if you want to change the image size ).
- Nine parameters: the most complex
drawImage
The preceding five parameters are included. The other four parameters are used to set the position and height of the source image. These parameters allow you to dynamically crop the source image before displaying the image.
The following are examples of the above three 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
.
Pixel-level operations
The 2D Context API provides three methods for Pixel-level operations:createImageData
,getImageData
, And
putImageData
.
ImageData
The object stores the pixel value of the image. Each object has three attributes:Width,HeightAnd
Data.DataThe attribute type is CanvasPixelArray, which is used for storage.width*height*4
Pixel value. Each pixel has an RGB value and a transparency alpha value (the value ranges from 0
255, including alpha !). The pixel sequence is stored from left to right, from top to bottom, by row.
To better understand its principles, 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 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 have implemented createImageData
. In the supported browsers getImageData
Method acquisition ImageData
Object. See the sample code.
PassImageData
Many functions can be completed. For example, Image filters or mathematical visualization (such as fragment and other special effects) can be implemented ). The following special effects implement a simple Color Reversal 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 with this filter
Image (figure 3 is the source image ).
Figure 4: Color Reversal Filter
Text
Although the Text API is supported only in the latest WebKit version and Firefox 3.1 nightly build, I decided to introduce the Text API here to ensure the integrity of the article.
context
You can set the following text attributes for an object:
font
: Text font, same as attributeAttribute
textAlign
: Horizontal alignment of text. Optional property values:start
,end
,left
,
right
,center
. Default Value:
start
.
textBaseline
: Vertical alignment of text. Optional property values:top
,hanging
,middle
,
alphabetic
,ideographic
,bottom
. Default Value:alphabetic
.
There are two ways to draw text:fillText
AndstrokeText
. First draw bandFillStyleFilled text, which is drawn onlyStrokeStyleBorder text. The two parameters are the same: the coordinates of the text and text to be drawn (x, y. There is also an optional option-maximum width. If necessary, the browser will reduce the text so that it can adapt to the specified width.
Text alignment attributes that affect text and settings
The relative position of the (x, y) coordinate.
The following is an example of drawing "hello world" text in the 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 shows it.
Figure 5: Text Effect
Shadow
Currently, only Konqueror and Firefox 3.1 build support the Shadows API. The API attributes are:
shadowColor
: Shadow color. The value is consistent with the CSS color value.
shadowBlur
: Sets the shadow blur level. The larger the value, the blurrier the shadow. The effect is the same as that of the Gaussian blur filter in Photoshop.
shadowOffsetX
AndshadowOffsetY
: The offset between x and y of the shadow, in pixels.
The following is an example of 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
Color gradient
In addition to the CSS color, fillStyle
AndstrokeStyle
Attribute can be setCanvasGradient
Object. -- PassCanvasGradient
You can use color gradient for lines and fills.
To createCanvasGradient
Object, you can use two methods:createLinearGradient
AndcreateRadialGradient
. The former creates a linear color gradient, and the latter creates a circular color gradient.
After creating a color gradient object, you can useaddColorStop
Method to add the color median.
The following code demonstrates how to use a color gradient:
// 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'); // redgradient1.addColorStop (0.5,' # ff0'); // yellowgradient1.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 have also prepared a more complex example using linear color gradient, shadow, and text. The effect is shown in figure 7.
Figure 7: Linear color gradient example
Canvas demo
If you want to know what you can do with Canvas, 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
Section
Canvas isHTML5. One of the most promising features has been supported by most Web browsers. Canvas helps you create games and enhance the graphic user interface. 2D context
The API provides a large number of graphic rendering functions-I hope you will learn more about the use of canvas through this article, and you are interested in learning more!