Comments: This article introduces you to the HTML5 Canvas API for programming. If you have any requirements, please refer to it.
The Code is as follows:
<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"/>
The Code is as follows:
// 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. moveTo (70,140 );
Context. lineTo (140, 70 );
// Draw the line to the Canvas
Context. 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
The Code is as follows:
// 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 drawing context to the bottom right
Context. translate (70,140 );
// Draw the same line segment as the previous line segment starting from the origin
Context. beginPath ();
Context. moveTo (0, 0 );
Context. lineTo (70,-70 );
Context. stroke (); </p> <p> 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
The Code is as follows:
Function createCanopyPath (context ){
// Draw the tree canopy
Context. beginPath (); </p> <p> context. moveTo (-25,-50 );
Context. lineTo (-10,-80 );
Context. lineTo (-20,-80 );
Context. lineTo (-5,-110 );
Context. lineTo (-15,-110); </p> <p> // vertex of the tree
Context. lineTo (0,-140); </p> <p> context. lineTo (15,-110 );
Context. lineTo (5,-110 );
Context. lineTo (20,-80 );
Context. lineTo (10,-80 );
Context. lineTo (25,-50 );
// Connection start point, closed path
Context. closePath ();
} </P> <p> function drawTrails (){
Var canvas = document. getElementById ('diagonal ');
Var context = canvas. getContext ('2d '); </p> <p> context. save ();
Context. translate (130,250); </p> <p> // create a path showing the canopy
CreateCanopyPath (context); </p> <p> // draw the current path
Context. stroke ();
Context. restore ();
} </P> <p> window. addEventListener ("load", drawTrails, true );
Stroke Style
Through the stroke mode, you can make the canopy look more authentic.
The Code is as follows:
// Widen the line
Context. lineWidth = 4;
// The joining Point of the smooth path
Context. 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
The Code is as follows:
Context. save ();
Context. translate (-10,350 );
Context. beginPath (); </p> <p> // The first curve is bent to the upper right corner.
Context. moveTo (0, 0 );
Context. quadraticCurveTo (170,-50,260,-190); </p> <p> // bend to the bottom right
Context. quadraticCurveTo (310,-250,410,-250); </p> <p> // Draw the path in a wide brown stroke
Context. strokeStyle = '#663300 ';
Context. lineWidth = 20;
Context. stroke (); </p> <p> // 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.
The Code is as follows:
// Load the image
Var bark = new Image ();
Bark. src = "bark.jpg"; </p> <p> // call the plotting function after the image is loaded.
Bark. 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
The Code is as follows:
// Create a level 3 horizontal gradient used as the trunk texture
Var trunkGradient = context. createLinearGradient (-5,-50, 5,-50); </p> <p> // the left edge of the trunk is generally Brown.
TrunkGradient. addColorStop (0, '#663300'); </p> <p> // color of the left-to-left position in the middle of the trunk
TrunkGradient. addColorStop (0.4, '#996600'); </p> <p> // the color of the right edge must be darker.
TrunkGradient. addColorStop (1, '#552200'); </p> <p> // fill the trunk with Gradient
Context. fillStyle = trunkGradient;
Context. fillRect (-5,-50, 10, 50 );
// Create a vertical gradient to use the projection of the canopy on the trunk
Var canopyShadow = context. createLinearGradient (0,-50, 0, 0 );
// The starting point of the projection gradient is the black color with a transparency of 50%.
CanopyShadow. addColorStop (0, 'rgba (0, 0, 0, 0.5 )');
// Vertical downward, gradient quickly gradient to completely transparent within a short distance, beyond the length
// There Is No projection on the trunk
CanopyShadow. addColorStop (0.2, 'rgba (0, 0, 0, 0.0) '); </p> <p> // fill in the projection gradient on the trunk
Context. fillStyle = canopyShadow;
Context. fillRect (-5,-50, 10, 50 );
Background Image
The Code is as follows:
// Load the image
Var gravel = new Image ();
Gravel. src = "gravel.jpg ";
Gravel. onload = function (){
DrawTrails ();
} </P> <p> // use the background image to replace the brown thick lines.
Context. 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.
The Code is as follows:
// Draw the first tree at X = 130, Y = 250
Context. save ();
Context. translate (130,250 );
DrawTree (context );
Context. restore (); </p> <p> // draw the second tree at X = 260, Y = 500
Context. save ();
Context. translate (260,500); </p> <p> // enlarge the height and width of the second tree to 2 times that of the original one.
Context. scale (2, 2 );
DrawTree (context );
Context. restore ();
Rotate
Rotating Images
The Code is as follows:
Context. save ();
// The rotation angle is measured in radians.
Context. rotate (1.57 );
Context. drawImage (myImage, 0, 0,100,100); </p> <p> context. restore ();
How to use a transform
The Code is as follows:
// Save the current status
Context. save (); </p> <p> // The value of X increases with the value of Y,
// You can create a shaded tree.
// After the transformation is applied, all coordinates are multiplied by the matrix.
Context. transform (1, 0,
-0.5, 1,
, 0); </p> <p> // in the Y axis, change the shadow height to 60%.
Context. scale (1, 0.6); </p> <p> // fill the trunk with a black transparency of 20%
Context. fillStyle = 'rgba (0, 0, 0, 0.2 )';
Context. fillRect (-5,-50, 10, 50); </p> <p> // use the existing shadow effect to re-draw the tree
CreateCanopyPath (context );
Context. fill (); </p> <p> // 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.
The Code is as follows:
// Draw text on the canvas
Context. save (); </p> <p> // set the font size to 60 and the font to Impact.
Context. font = "60px impact"; </p> <p> // fill color
Context. fillStyle = '#996600 ';
// Center
Context. textAlign = 'center'; </p> <p> // draw 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 Code is as follows:
// Black color, 20% transparency
Context. shadowColor = 'rgba (0, 0, 0, 0.2) '; </p> <p> // move 15px to the right and 10px to the left
Context. shadowOffsetX = 15;
Context. shadowOffsetY =-10; </p> <p> // 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.