HTML5-Canvas (1)

Source: Internet
Author: User
Tags linecap

HTML5-Canvas (1)
Canvas is actually not so mysterious. It is almost an H5 tag, similar to other HTML tags: <canvas> </canvas> canvas itself has no drawing capability, all plotting work is implemented through js. In js, we usually get the canvas to be operated through getElementById (this means we have to set an id for the canvas ): copy the Code <canvas id = "myCanvas"> </canvas> <script> var c = document. getElementById ("myCanvas"); // obtain the code of the canvas to be operated // the code of the canvas to be operated... </script> copy the code. It is best to set the width and height of the canvas at the beginning (if the width and height are not set, the browser sets the canvas size to 300 in width and 100 pixels in height by default. css cannot be used to set the canvas size (it will be stretched). It is recommended to write the canvas label directly: <canvas id = "myCanvas" width = "200" height = "200"> </canvas> can also be set in the js script: copy the Code <canvas id = "myCanvas"> </canvas> <script> Var c = document. getElementById ("myCanvas"); c. width = 200; c. height = 200; </script> one thing you need to know about the canvas size when copying code is that all the subsequent drawing operations on the canvas are invisible beyond the size range. As the name suggests, you can regard canvas as a canvas. The size of canvas is the width and height we set. No matter how you draw it, the area outside the canvas is naturally invisible. For Some browsers that do not support the canvas function, you can directly write some replacement content in the canvas label. When the browser does not support the canvas function, the following information is displayed: <canvas id = "myCanvas" width = "200" height = "200" style = "border: solid 1px # CCC;"> canvas is not supported in your browser, we recommend that you use the latest version of Chrome </canvas>. Before you talk about how to draw images on the canvas, let's talk about it first. getContext ("2d .. GetContext () is the Drawing Object/method of canvas. To allow canvas to perform drawing, you must first obtain the. getContext () object of canvas for execution.. GetContext () only accepts one parameter. this parameter is used to obtain the drawing environment of the canvas, for example. getContext ("2d") indicates that the canvas's drawing environment is a 2D plane (you can draw text, straight lines, arcs, rectangles, circles, etc ). Currently, H5 only supports the 2D environment, and the 3D drawing function will be available in the near future. (So we can translate "getContext" into "get drawing environment".) In theory, let's take a small example to start with the simplest line: copy the Code <canvas id = "myCanvas" width = "200" height = "200" style = "border: solid 1px # CCC;"> canvas is not supported in your browser, we recommend that you use the latest Chrome version </canvas> <script> var c = document. getElementById ("myCanvas"); var ctx = c. getContext ("2d"); // obtain the 2D drawing environment object ctx of the canvas. moveTo (); // defines the position at which the painting begins ctx. lineTo (150); // draw a straight line. The coordinates of the end point are x =, y = 50ctx. stroke (); // stroke </script>: GetContext ("2d :. moveTo (x coordinate, y coordinate) can be understood as positioning the position of the paint brush on the canvas (note that the coordinates defined by all drawing methods are relative to canvas rather than browser windows, for canvas, the coordinates of the vertices in the upper left corner are (0, 0 )). lineTo (x coordinate, y coordinate), as its name implies, is to draw a straight line to a certain point, which is easy to understand. You need to know that this method only performs Path movement, without any visual drawing effect (coloring and stroke ). if you have played AfterEffect in the stroke () stroke method, it will be clear that the painting without applying the stroke effect to the motion path does not have the stroke effect, and the canvas is the same, to achieve visual effects on the trajectory of a motion path, we need to use the corresponding color/stroke method. Since then, we have easily drawn a black line, but if we want to draw a red or hidden line segment, what should we do? The answer is simple. Use ctx. strokeStyle to set the stroke color. Let's draw three red lines: copy the Code <canvas id = "myCanvas" width = "200" height = "200" style = "border: solid 1px # CCC; margin: 30px; "> your browser does not support canvas. We recommend that you use the latest version of Chrome </canvas> <script> var c = document. getElementById ("myCanvas"); var ctx = c. getContext ("2d"); // obtain the 2D drawing environment object ctx of the canvas. moveTo (); // move the "paint brush" to the coordinate () ctx. lineTo (); // draw a straight line from the previous point (). the coordinate of the end point is () ctx. lineTo (20,100); // draw a straight line from the previous vertex (20,100). the coordinate of the ending vertex is () ctx. moveTo (90, 90); // move the "paint brush" to the coordinate (90, 90) ctx. lineTo (80,150); // draw a straight line from the previous vertex (60, 60). The coordinate of the ending vertex is (80,150) ctx. strokeStyle = "red"; // set the stroke color to red, as long as it is written in. you can use ctx before the stroke () method. stroke (); // stroke </script> the implementation principle is not described here because it is clear to copy the code comments. The effect is as follows: note that when creating a path, you must add moveTo (x, y). Otherwise, the motion track of the first lineTo () will not be included in the drawing (the browser will think that the starting point of the motion track is not obtained, ignore this line segment ). Another problem is that if we have two lines above (well, one line, one line), we want the first line to be blue and the second line to be red, what should I do? You will naturally do the following: copy the Code <script> var c = document. getElementById ("myCanvas"); var ctx = c. getContext ("2d"); ctx. moveTo (0, 0); ctx. lineTo (150,50); ctx. lineTo (20,100); ctx. strokeStyle = "blue"; // set the stroke color to blue ctx. stroke (); ctx. moveTo (90,90); ctx. lineTo (80,150); ctx. strokeStyle = "red"; // set the stroke color to red ctx. stroke (); </script> copy the code, but when running the script, you will find that the line is not only blue, but also Red: this is because when canvas colors the path for the second time, it colors all the paths of the previous path, unless we let canvas know that Line and line should be independent paths. We can use. beginPath (): copy the Code <script> var c = document. getElementById ("myCanvas"); var ctx = c. getContext ("2d"); ctx. moveTo (0, 0); ctx. lineTo (150,50); ctx. lineTo (20,100); ctx. strokeStyle = "blue"; // set the stroke color to blue ctx. stroke (); ctx. beginPath (); // tells canvas that we want to re-draw a new path. The previously drawn items have no relation to ctx. moveTo (90,90); ctx. lineTo (80,150); ctx. strokeStyle = "red"; // set the stroke color to red ctx. stroke (); </script> some friends who copy the Code cannot figure out beginPath at the beginning. () Purpose, I think it is enough to have moveTo (). In fact, beginPath () can achieve the effect of the isolation path above, to prevent the previous effect from being contaminated. Then. the value assignment method of strokeStyle. ctx is directly used above. strokeStyle = "red" to define the stroke color as red, But ctx. strokeStyle has three values: ctx. strokeStyle = color | gradient | pattern; // supports the assignment of "color/gradient/pattern brush" (1) first, let's look at the color assignment method, which is the same as our regular css assignment, supports the css3 color value standard. For example, copy the code // The following four formats are the same, indicating that the stroke color is "orange" ctx. strokeStyle = "orange"; ctx. strokeStyle = "# FFA500"; // # ctx in the rrggbb format. strokeStyle = "rgb (255,165, 0)"; // ctx in RGB format. strokeStyle = "rgba (255,165,)"; // a (Alpha) ), That is, the Transparent copy code (2) and then look at the gradient. This is slightly complicated: copy the code var c = document. getElementById ("myCanvas"); var ctx = c. getContext ("2d"); ctx. moveTo (0, 0); ctx. lineTo (150,50); ctx. lineTo (20,100); var grd = ctx. createLinearGradient (, 170,0); // defines a linear gradient object and sets the coordinates of the start and end points of the gradient line. The coordinate format is (start point x, start point y, end point x, end point y) grd. addColorStop (0, "black"); // defines the color of the starting point of the gradient line grd. addColorStop (0.5, "red"); // defines the grd color of the intermediate point of the gradient line. addColorStop (1, "yellow"); // defines the color of ctx at the end of the gradient line. s TrokeStyle = grd; // assign the gradient object to strokeStylectx. stroke (); // trace and copy the Code as follows: here we mention a concept called "gradient line". If you have never played design, you need to learn about the gradient, we can regard the LinearGradient (linear gradient, and radial/circular gradient RadialGradient) range as a rectangle (you can use professional design software such as Illustator and Photoshop to help you understand this ): at the beginning, we defined the code var grd = ctx for linear gradient objects. createLinearGradient (, 170,0) is almost equivalent to setting the starting point of the linear gradient line (), and the ending point is (170,0 ). Then we use addColorStop (gradient line position <0 ~ 1>, color) to set the gradient value, respectively in the gradient line 0, 0.5, 1 set the black, red, yellow, the gradient effect is as follows: Through ctx. strokeStyle = grd assigns the gradient value to the stroke method, and the stroke gets the gradient effect we want. (3) Finally, let's take a look at the pattern stroke method. strokeStyle is not called strokeColor because it not only supports color strokes but also supports pattern strokes (design friends may call stroke strokes more feel ). CreateLinerGradient (xstart, ystart, xend, yend) is required for linear gradient stroke. To set the pattern stroke, you must first create a canvasPattern object: createPattern (image, repetitionStyle) the image parameter indicates the pattern object. createElement ('img ') or new Image (), and then define its src value to create this object. The repetitionStyle parameter is easy to understand, that is, the pattern repetition form, the optional values include "repeat", "repeat-x", "repeat-y", and "no-repeat" (same as the optional values of css background-repeat, not described in detail ). Then we can try to write: copy the Code <body> <canvas id = "myCanvas" width = "200" height = "200" style = "border: solid 1px # CCC; margin: 30px; "> canvas is not supported in your browser. We recommend that you use the latest Chrome version </canvas> <script> var c = document. getElementById ("myCanvas"); var ctx = c. getContext ("2d"); pic = new Image (); // create an Image object, or pic = document. createElement ('img ') pic. src =" http://images.cnblogs.com/cnblogs_com/vajoy/558870/o_5.jpg "; // Defines the ing address of the image var redTexture = ctx. createPattern (pic, "repeat"); // defines the Pattern object, sets the fill Pattern to a pic image, and the fill form to tile ctx. strokeStyle = redTexture; // defines the stroke style as the Pattern stroke ctx set in the previous line. moveTo (80, 10); ctx. lineTo (10, 90); ctx. stroke (); </script> When copying the code, we only find that nine times of execution are not the expected image filling effect, but the default black stroke effect. Why? The reason is that the browser may have executed ctx before loading the image pic. stroke (). The solution is to let ctx execute the drawing after the image pic is loaded: copy the Code <canvas id = "myCanvas" width = "200" height = "200" style = "border: solid 1px # CCC; margin: 30px; "> your browser does not support canvas. We recommend that you use the latest version of Chrome </canvas> <script> var c = document. getElementById ("myCanvas"); var ctx = c. getContext ("2d"); pic = new Image (); // create an Image object, or pic = document. createElement ('img ') pic. src =" http://images.cnblogs.com/cnblogs_com/vajoy/558870/o_5.jpg "; Pic. onload = patternFill; // execute the plotting function patternFill () when the image is loaded. {// define the plotting function var redTexture = ctx. createPattern (pic, "repeat"); ctx. strokeStyle = redTexture; ctx. moveTo (80, 10); ctx. lineTo (10, 90); ctx. lineWidth = 8; // defines the line segment width as 8 pixels ctx. stroke () ;}</script>. lineWidth = 8 to set the width of a line segment. Since then, we have learned three ways to assign values to strokeStyle, and also learned how to set the width of a line segment through ctx. lineWidth = lineWeight. Finally, let's learn two simple line segments: lineCap and lineJoin. (1) lineCap is used to set the shape (line cap) of the Line Segment endpoint. The value can be the default value of butt, that is, the line endpoint is a straight edge. The round line endpoint is a rounded corner line cap. square Line caps are added to the line endpoint. <canvas id = "myCanvas" width = "250" height = "120" style =" border: 1px solid # DDD; "> </canvas> <script> var c = document. getElementById ("myCanvas"); var ctx = c. getContext ("2d"); ctx. lineWidth = 10; ctx. beginPath (); ctx. lineCap = "butt"; ctx. moveTo (20, 10); ctx. lineTo (200,60); ctx. strokeStyle = "red"; ctx. stroke (); ctx. beginPath (); ctx. lineCap = "round"; ctx. moveTo (30,90); ctx. lineTo (200,40); ctx. strokeStyle = "blue"; ctx. stroke (); ctx. beginPath (); ctx. lineCap = "square"; ctx. moveTo (10, 30); ctx. lineTo (200,80); ctx. strokeStyle = "green"; ctx. stroke (); </script> the code copy effect is as follows: you may not see the difference between "butt" and "square" in this figure, however, students who know how to use AI to draw vectors should have a better understanding: (2) lineJoin is to set the outer Angle Type of the line intersection. Its value can be: miter default, the line intersection is the corner round line intersection is the corner bevel line intersection is the corner

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.