One, understand
HTML5 adds a very popular feature called elements. This element is responsible for setting up a region on the page that can then be dynamically drawn in JavaScript.
Like other components of the browser environment, it is made up of group apis, which are not supported by all browsers, including a 2D context with drawing capability, and a 3D context called WebGL. Currently, browsers that support this element support 2D context and text apis, but WebGL support is not good enough. Since WebGL is still experimental, it will be a long time before it is supported by all browsers.
Second, preparation
To use the element, you must first set its width and height attributes, specify the size of the area that can be drawn, and the content that appears in the start and end tags is the back information that will be displayed if the browser does not support it.
<canvas ID ="canvas" width="1000" height="500"> Your browser version does not support Canvas, you are advised to upgrade your browser </canvas>
Like other tag elements, the element’s DOM element object has the basic attributes height and width, which can be modified at will or styled with CSS. If you don’t add any styles, you won’t see the element on the page.
To draw on this canvas, you need to get the drawing context. That is, call the getContext () method and pass in the name of the context. Passing “2d” gets the 2D context object.
var ctx = canvas.getContext("2d")
But before you use the element, you finally check to see if the getContext () method exists.
<script> // Get canvas's DOM node var canvas = document.querySelector("#canvas"); If (ctx.getContext){var CTX = canvas.getContext("2d")} </script>Copy the code
2D context
Using the methods provided by the 2D drawing context, you can draw 2D shapes such as rectangles, arcs, and paths. The coordinates of the 2D context start at the upper left corner of the element. The origin coordinate is (0,0). All coordinates are calculated based on this origin. Width and height indicate the number of available pixels in both horizontal and vertical directions.
Four, about drawing
4.1 Fill and Stroke
The values of these two properties can be strings, gradient objects, and the default color is #000000, but support using CSS specified color values in any form
4.2 Drawing a Rectangle
Rectangles are the only shapes that can be drawn directly.
2Solid rectangle: fillRect (x, y, width, height)
Rectangles are the only shapes that can be drawn directly. Four parameters, x coordinate, y coordinate, width, height
Take a chestnut
<script> var canvas = document.querySelector("#canvas"); var ctx = canvas.getContext("2d"); Ctx. fillStyle="pink"; // Change the background color, the default background color is black. // draw a wide ctx.fillrect (100,100,200,200) at coordinates x and y; </script>Copy the code
The effect
4.2.2 Border Rectangle: strokeRect (X, Y, width, Height)
Four parameters, x coordinate, y coordinate, width, height
Take a chestnut
<script> var canvas = document.querySelector("#canvas"); var ctx = canvas.getContext("2d"); StrokeStyle = "deeppink" // draw a wide ctx.strokeRect(100,100,200,200) at coordinates x, y; </script>Copy the code
The effect
4.2.2 Clearing rectangles:ClearRect (x, y, width, height)
A clear rectangle is not visible when used alone on a page. It is used within a graphic area to clear an area
Four parameters, x coordinate, y coordinate, width, height
Take a chestnut
<script> var canvas = document.querySelector("#canvas"); var ctx = canvas.getContext("2d"); ctx.fillStyle="pink"; // change the background color ctx.fillrect (100,100,200,200)// the default background color is black // draw a clear rectangle to clear an area on the image ctx.clearrect (150,150,100,100); </script>Copy the code
The effect
4.3 Path Drawing
Complex shapes and lines can be created by drawing paths. The beginPath () method is called to begin drawing a new path. The method is then called to actually draw the path.
4.3.1 Drawing a Line
The order in which you draw the line
Start drawing ctx.beginPath() 2. Start drawing CTx.moveto (x,y); Ctx.lineto (x,y); 3. 4. Draw: ctx.stroke(); 5. Finish drawing: ctx.closepath ();
The parameters x and y are coordinates
Take a chestnut
<script> var canvas = document.querySelector("#canvas"); var ctx = canvas.getContext("2d"); // Start drawing ctx.beginPath(); // Draw the starting point ctx.moveto (100,150); // Draw the endpoint ctx.lineto (200,250); / / draw the CTX. Stroke (); // End path ctx.closepath (); </script>Copy the code
The effect
4.3.1 Draw a line segment triangle
Draw triangle order
Start drawing ctx.beginPath() 2. Start drawing CTx.moveto (x,y); 3. Draw a bit: ctx.lineTo(x1,y1); Ctx. lineTo(x2,y2); Ctx.lineto (x,y); 4. Draw: ctx.stroke(); 5. Finish drawing: ctx.closepath ();
The parameters x and y are coordinates
Take a chestnut
<script> var canvas = document.querySelector("#canvas"); var ctx = canvas.getContext("2d"); // Start path ctx.beginPath(); // Start point ctx.moveto (450,100); / / the end CTX. LineTo (600100); // continue to draw ctx.lineTo(600,200); Ctx. lineTo(450,100); / / draw the CTX. Stroke (); // End path ctx.closepath (); </script>Copy the code
The effect
4.3.2 Drawing solid triangles
Draw triangle order
Start drawing ctx.beginPath() 2. Start drawing CTx.moveto (x, y); 3. Draw a bit: ctx.lineTo(x1, y1); Ctx. lineTo(x2, y2); Ctx.lineto (x, y); 4. Draw: ctx.fill(); 5. Finish drawing: ctx.closepath ();
The parameters x and y are coordinates
Take a chestnut
<script> var canvas = document.querySelector("#canvas"); var ctx = canvas.getContext("2d"); // Start path ctx.beginPath(); // Start point ctx.moveto (450,100); / / the end CTX. LineTo (600100); // continue to draw ctx.lineTo(600,200); Ctx. lineTo(450,100); // Change the background color ctx.fillStyle="pink"; / / draw the CTX. The fill (); // End path ctx.closepath (); </script>Copy the code
The effect
4.3.3 Drawing circles
Arc (x,y, Radius, starting Angle, ending Angle, direction (true for counterclockwise, false for clockwise));
Parameters respectively represent:
Parameters for drawing an arc are: center of arc x coordinate, y coordinate, radius, starting Angle (starting at 3 o ‘clock), ending Angle and direction (true means counterclockwise, false means clockwise).
Take a chestnut
<script> var canvas = document.querySelector("#canvas"); var ctx = canvas.getContext("2d"); // Start path ctx.beginPath(); // draw circle ctx.arc(650,350,100,0, math.pi *2,false); ctx.fill(); //ctx.stroke(); The hollow circular CTX. ClosePath (); </script>Copy the code
The effect
Note: When drawing arcs, just change the ending Angle. Math.PI*2, for plotting 2 PI radians, is a full circle.
4.4 Drawing Text
There are two main methods for drawing text.
FillText () : draws text with the fillStyle property; StrokeText () : Stroke the text using the strokeStyle property;
FillText () is commonly used because it mimics the normal display of text on a web page.
Both methods can take four arguments. Draws the text string, x coordinates, y coordinates, and optionally the maximum pixel width
However, both methods are based on three attributes: font: text style, size, and font textAlign: indicates the alignment of the text textBaseline: indicates the baseline of the text
Take a chestnut
<script> var canvas = document.querySelector("#canvas"); var ctx = canvas.getContext("2d"); Font = "bold 20px Arial" ctx.textAlign = "center" ctx.textBaseline = "middle" ctx.fillText(" text message ",300,100) </script>Copy the code
The effect
Additional information
Because we set textAlign to center and textBaseline to middle, the coordinate (300,100) represents the coordinates of the horizontal and vertical end points of the text. If textAlign is set to start, the X coordinate represents the position at the left end of the text (the language read from left to right); Set to end, the x-coordinate represents the position of the right end of the text.
chestnuts
<script> var canvas = document.querySelector("#canvas"); var ctx = canvas.getContext("2d"); Font = "bold 20px Arial" ctx.textAlign = "center" ctx.textBaseline = "middle" ctx.filltext (" text message ",300,100) Ctx.textalign = "start" ctx.filltext (" text ",300,150) ctx.textalign = "end" ctx.filltext (" text ",300,200) </script>Copy the code
The effect
4.5 transform
By changing the context, you can draw the processed image onto the canvas. 2 d drawing context supports a variety of basic drawing transformation, creating context, with the default initialization of transform matrix, under the default transformation matrix, all the processing according to the description draw directly, for rendering context application transformation, can lead to use different transformation matrix application processing, thus produce different results.
The rotate (Angle) transform can be modified by using the following method: Rotate the Angle radian around the origin
Scale (scaleX, scaleY) : Scale the image by multiplying it in the x direction by scaleX and in the y direction by scaleY. The default value for both scaleX and scaleY is 1.0
Translate (x, y) : Move the origin of the coordinate to (x, y). After this operation, the coordinate (0,0) becomes the point previously represented by (x, y).
Since there is no special chestnut to help digestion, there will be good examples to supplement _**
4.6 Drawing An Image
2D drawing context has built-in support for object images. If you want to draw an image onto a canvas, use the drawImage () method
DrawImage (image, x, y) : draws an image at the coordinate (image, x, y). The size of the image is consistent with the original size
DrawImage (image, x, y, width, height) : drawImage (image, x, y, width, height) : drawImage (image, x, y, width, height)
Take a chestnut
<script> var canvas = document.querySelector("#canvas"); var ctx = canvas.getContext("2d"); var image = new Image(); image.src="biyezhao.jpg"; Image.onload = function(){ctx.drawImage(image,10,10); } </script>Copy the code
DrawImage (image, x, y, width, height, x1, y2, width2, height2) : To draw a region of an image into the context
The effect
The parameters represent the image to be drawn, the x coordinate of the source image, the Y coordinate of the source image, the width of the source image, the height of the source image, the x coordinate of the target rabbit, the Y coordinate of the target image, the width of the target image, and the height of the target image
Take a chestnut
<script> var canvas = document.querySelector("#canvas"); var ctx = canvas.getContext("2d"); var image = new Image(); image.src="biyezhao.jpg"; Image.onload = function(){ctx.drawImage(image,10,10); //ctx.drawImage(image,10,10,100,100); / / draw part of a capture image in the canvas CTX. DrawImage (image, 500360100100,50,50,100,100); } </script>Copy the code
4.7 the shadow
The 2D context automatically draws shadows for shapes or paths based on the values of the following attributes. ShadowColor: shadowColor in CSS color format. The default color is black. ShadowOffsetX: The shadow offset of a shape or path along the x axis. Default is 0. ShadowOffsetY: Shadow offset of a shape or path along the Y-axis. The default value is 0. “ShadowBlur” : indicates the number of pixels that blur. The default value is 0.
Take a chestnut
<script> var canvas = document.querySelector("#canvas"); var ctx = canvas.getContext("2d"); ctx.shadowOffsetX = 5; ctx.shadowOffsetY = 5; ctx.shadowBlur = 4; CTX. ShadowColor = "rgba,0,0,0.5 (2)"; CTX. FillStyle = "yellowgreen" CTX. FillRect (100100200200); </script>Copy the code
4.8 the gradient
The gradient is represented by the CanvasGradient instance and is easily created and modified from a 2D context. To create a new linear gradient, call the createLinearGradient () method.
The four parameters createLinearGradient (x1, y1, x2, y2) respectively represent the coordinates of starting point X, starting point Y, ending point X, and ending point Y. Calling this method creates a gradient of the specified size and returns an instance of the CanvasGradient object.
After creating the gradient object, use the addColorStop () method to specify the color standard. This method takes two parameters, the CSS color position and the CSS color value.
The color code position is a number between 0 (the starting color) and 1 (the ending color).
Take a chestnut
<script> var canvas = document.querySelector("#canvas"); var ctx = canvas.getContext("2d"); var image = new Image(); Var gradient = CTX. CreateLinearGradient (100,100,300,300); // Specify the color gradient. AddColorStop (0,"red"); gradient.addColorStop(1,"blue"); // The gradient at this time refers to a gradient from (100,100) to (300,300) // on the canvas, starting with red and ending with blue, FillStyle // or strokeStyle set this object ctx.fillstyle = gradient; CTX. FillRect (100100100100); </script>Copy the code
The effect
For the gradient to cover the entire rectangle, the coordinates of the rectangle and the gradient must match. If the rectangle is not drawn in the right place, only part of the gradient may appear.
4.9 model
Patterns are simply repeated images that can be used to fill or stroke shapes. To create a new schema, call the createPattern () method, passing in two parameters. An HTML img tag element, a string that is repeated or not. Repeat, no-repeat, repeatX,repeatY
Take a chestnut
var canvas = document.querySelector("#canvas"); var ctx = canvas.getContext("2d"); var image = new Image(); image.src="1.PNG"; image.onload = function(){ pattern = ctx.createPattern(image,"repeat"); ctx.fillStyle = pattern; ,0,700,400 CTX. FillRect (0)} < / script >Copy the code
Make up a little bit of knowledge
LineJoin: When two lines intersect, the setting returns the type of edges and corners created. Bevel: creates bevel angles round: creates rounded corners miter: creates sharp corners by default