Check browser support
<script type="text/javascript"> try { document.createElement("Canvas").getContext("2d"); document.getElementById("support").innerHTML = "OK"; } catch (e) { document.getElementById("support").innerHTML = e.message; } </script>
Join Canvas
<canvas id="diagonal" style="border:1px solid blue;" width="200" height="200"/>
Diagonal Line
// Obtain the Canvas Element and Its Drawing context var canvas = document. getElementById ("diagonal"); var context = canvas. getContext ("2d"); // use absolute coordinates to create a path context. beginPath (); context. VPC: moveTo (70,140); context. lineTo (140, 70); // draw the line to the context on the Canvas. stroke ();
Transform
You can achieve the same effect as above by means of transformation (scaling, translation, and rotation.
Draw a diagonal line by means of transformation
// Obtain the Canvas Element and Its Drawing context var canvas = document. getElementById ("diagonal"); var context = canvas. getContext ("2d"); // Save the current drawing status context. save (); // move the context of the drawing to the lower right. translate (70,140); // start from the origin and draw the same line string as the preceding context. beginPath (); context. moveTo (0, 0); context. lineTo (70,-70); context. stroke (); context. restore ();
Path
The path in the HTML5 Canvas API represents any shape you want to render.
BeginPath (): No matter what type of image is drawn, the first one to be called is beginPath. This simple function does not contain any parameters. It is used to notify canvas to start drawing a new graph.
MoveTo (x, y): Move the current position to the new target coordinate (x, y) without drawing ).
LineTo (x, y): Not only moves the current position to the new target coordinate (x, y), but also draws a straight line between the two coordinates.
ClosePath (): This function acts like lineTo. The only difference is that closePath automatically takes the starting coordinate of the path as the target coordinate. It also notifies the canvas that the current drawing has been closed or has formed a fully closed area, which is useful for future filling and stroke.
Create a pine tree canopy
Function createCanopyPath (context) {// Draw the tree canopy context. beginPath (); context. moveTo (-25,-50); context. lineTo (-10,-80); context. lineTo (-20,-80); context. lineTo (-5,-110); context. lineTo (-15,-110); // context of the vertex of the tree. lineTo (0,-140); context. lineTo (15,-110); context. lineTo (5,-110); context. lineTo (20,-80); context. lineTo (10,-80); context. lineTo (25,-50); // connection start point, closing path context. closePath ();} function drawTrails () {var canvas = document. getElementById ('diagonal'); var context = canvas. getContext ('2d '); context. save (); context. translate (130,250); // create the path createCanopyPath (context) for the performance canopy; // draw the current path context. stroke (); context. restore ();} window. addEventListener ("load", drawTrails, true );
Stroke Style
Through the stroke mode, you can make the canopy look more authentic.
// Broaden the context. lineWidth = 4; // The context of the smooth path. lineJoin = 'round '; // color context. strokeStyle = '#663300'; // draw the current path context. stroke ();
Fill Style
context.fillStyle = "#339900"; context.fill();
Draw a rectangle
We add a trunk for the tree.
context.fillStyle = '#663300'; context.fillRect(-5, -50, 10, 50);
Draw a curve
Context. save (); context. translate (-10,350); context. beginPath (); // The first curve is bent to the upper right corner of the context. moveTo (0, 0); context. quadraticCurveTo (170,-50,260,-190); // bend the context to the lower right corner. quadraticCurveTo (310,-250,410,-250); // Draw the path in a wide brown stroke context. strokeStyle = '#663300'; context. lineWidth = 20; context. stroke (); // Restore the previous canvas state context. restore ();
Insert an image into the Canvas
You must wait until the image is fully loaded before you can operate on it. Browsers usually load images asynchronously when page scripts are executed. If you try to present images to the canvas before they are fully loaded, the canvas will not display any images. Therefore, note that before rendering, make sure that the image has been loaded.
// Load the Image var bark = new Image (); bark. src = "bark.jpg"; // call the bark function after the image is loaded. onload = function () {drawTrails ();}
Show image:
// Fill with the background pattern and use it as the background context. drawImage (bark,-5,-50, 10, 50) of the trunk );
Gradient
Three steps are required to use the gradient:
(1) create a gradient object
(2) set the color of the gradient object and specify the transition mode.
(3) set gradient for the fill style or stroke style in context
// Create a third-level horizontal gradient var trunkGradient = context. createLinearGradient (-5,-50, 5,-50); // the left edge of the trunk is generally brown trunkGradient. addColorStop (0, '#663300'); // the color of the left-to-left position in the middle of the trunk to talk about trunkGradient. addColorStop (0.4, '#996600'); // the color of the right edge must be a bit deeper than trunkGradient. addColorStop (1, '#552200'); // fill the trunk context with gradient. fillStyle = trunkGradient; context. fillRect (-5,-50, 10, 50); // create a vertical gradient to use the projection var canopyShadow = context on the trunk of the canopy. createLinearGradient (0,-50, 0, 0); // the starting point of the projection gradient is the black canopyShadow with the transparency of 50%. addColorStop (0, 'rgba (0, 0, 0, 0.5) '); // vertical downward direction, gradient quickly gradient to completely transparent within a short distance, no canopyShadow is projected on the trunk outside the length of this section. addColorStop (0.2, 'rgba (0, 0, 0, 0.0) '); // fill in the projection gradient context on the trunk. fillStyle = canopyShadow; context. fillRect (-5,-50, 10, 50 );
Background Image
// Load the Image var gravel = new Image (); gravel. src = "gravel.jpg"; gravel. onload = function () {drawTrails ();} // use the background image to replace the context of the brown coarse line. strokeStyle = context. createPattern (gravel, 'repeat'); context. lineWidth = 20; context. stroke ();
The second parameter of context. createPattern is a repetitive tag. You can select an appropriate value in Table 2-1.
Tile Mode |
Meaning |
Repeat |
(Default) the image is tiled in two directions. |
Repeat-x |
Horizontal Tile |
Repeat-y |
Vertical Tile |
No-repeat |
The image is only displayed once, not tiled |
Zoom
The scale function context. scale (x, y): x, y represents the values in the x and y dimensions. When a canvas displays an image, each parameter is transmitted to the image to be enlarged (or reduced) in the current direction. If the value of x is 2, it means that all the elements in the image will become twice the width, if the value of y is 0. 5. The image is half the height of the previous image.
// Draw the context of the first tree at X = 130, Y = 250. save (); context. translate (130,250); drawTree (context); context. restore (); // draw the second context tree at X = 260, Y = 500. save (); context. translate (260,500); // enlarge the height and width of the second tree to 2 times the original context. scale (2, 2); drawTree (context); context. restore ();
Rotate
Rotating Images
Context. save (); // The Rotation Angle Parameter is in radians. context. rotate (1.57); context. drawImage (myImage, 0, 0,100,100); context. restore ();
How to use a transform
// Save the current context. save (); // The value of X increases with the value of Y. With the help of the stretch transformation, // you can create a tree that is used as the skew of the Shadow. // after the transformation is applied, all coordinates are multiplied by the matrix context. transform (1, 0,-0.5, 1, 0, 0); // in the Y axis, change the shadow height to the original 60% context. scale (1, 0.6); // fill the trunk context with a black transparency of 20%. fillStyle = 'rgba (0, 0, 0, 0.2) '; context. fillRect (-5,-50, 10, 50); // use the existing shadow effect to re-draw the tree createCanopyPath (context); context. fill (); // restore the canvas status context. restore ();
Text
Context. fillText (text, x, y, maxwidth): text content, x, y specifies the text location, maxwidth is an optional parameter, limit the text location.
Context. strokeText (text, x, y, maxwidth): text content, x, y specifies the text location, maxwidth is an optional parameter, limit the text location.
// Draw the text context on the canvas. save (); // The font size is 60 and the font is Impact context. font = "60px impact"; // fill the color context. fillStyle = '#996600'; // center context. textAlign = 'center'; // draw the text context. fillText ('Happy Trails! ', 200, 60,400); context. restore ();
Shadow
You can control the shadow by using several global context attributes.
Attribute |
Value |
Remarks |
ShadowColor |
Color values in any CSS |
Available transparency (alpha) |
ShadowOffsetX |
Pixel value |
If the value is positive, the shadow is moved to the right. If the value is negative, the shadow is moved to the left. |
ShadowOffsetY |
Pixel value |
If the value is positive, the shadow is moved downward. If the value is negative, the shadow is moved upward. |
ShadowBlur |
Gaussian Blur Value |
The greater the value, the blurrier the shadow edge. |
// The color is black and the transparency is 20%. shadowColor = 'rgba (0, 0, 0, 0.2) '; // move 15px to the right and 10px context to the left. shadowOffsetX = 15; context. shadowOffsetY =-10; // slightly blur the shadow context. shadowBlur = 2;
Pixel data
Context. getImageData (sx, sy, sw, sh): sx, xy determine a point, sw: width, sh: height.
This function returns three attributes: width, the number of pixels in each row, and height, the number of pixels in each column.
A bunch of data arrays containing RGBA values (values: red, green, blue, and transparency) for each pixel obtained from the canvas ).
Context. putImageData (imagedata, dx, dy): allows developers to input a set of image data. dx and dy are used to specify the offset. If they are used, the function will jump to the specified canvas to update the data.
Displays the uploaded pixel data.
Canvas. toDataUrl: You can obtain the data currently presented on the canvas by programming. The obtained data is saved in text format, and the browser can parse it into an image.