Objective
This article details the API of the canvas canvas. Said is a detailed introduction, but also just a few common APIs and simple examples and instructions. LZ himself has not read all, the next chapter will introduce some of the remaining content.
In this example, the LZ added a note to simply introduce the API is really boring, and not so easy to understand, look at the code to see the most direct effect.
Canvas APIs
Introduction to the Canvas Basics API
In the initialization JavaScript function, get the canvas's DOM object with the canvas tag ID, and use the GetContext () method to get the canvas's "2d" context object, and then invoke the canvas API drawing using the context object.
Linear
The ability to draw straight lines can be achieved using a combination of Beginpath (), MoveTo (), lineTo () and Stroke () methods.
Method Beginpath () defines the beginning of a new path-drawing action.
Method MoveTo () creates a new sub-path for the specified point, and we can
The MoveTo () method is considered to be used to position the drawing mouse (the starting point of the line, because all the drawing lines are related to it, which we call the context point).
Method LineTo () draws a line from the mouse anchor point to the point specified in the method parameter.
Method Stroke () assigns a color to the line that is drawn and makes it visible. If no specific color is specified, the black line is used by default.
Contextual Object Context Properties
Context.linewidth = 5; Set width
Context.strokestyle = ' Blue '; Set color
Context.linecap = ' round '; Sets the line end style, with the optional value butt (default), round, and square.
Examples such as the following
View Code
Effect
Arc
The way to draw an arc is arc (). Each arc needs to be determined by the center point, radius, start angle (radians n*math.pi), End angle (Radian M*math.pi), and drawing direction (clockwise or counterclockwise true). such as Context.arc (x, y, radius, startangle, Endangle, anticlockwise);
Two times curve
Two times the curve is drawn using the Quadraticcurveto () method. Each two-time curve is defined by a context point, a control point, and a termination point.
Context.quadraticcurveto (Controlx, Controly, EndX, EndY);
Bezier curve
Draw Bezier curves using Method Beziercurveto (). Each Bezier curve needs to be determined by a context point, two control points, and a termination point. Such as:
Context.beziercurveto (controlX1, controlY1, controlX2, controlY2, EndX, EndY);
Rounded Corners
Draw rounded corners using the method ArcTo (). This method requires a control point, a termination point, and a radius as the necessary parameters. Such as:
Context.arcto (Controlx,controly,endx,endy,radius);
Draw Path
The path is made up of a multi-sliver path connection. The end point of each sliver path is used as the new context point. We can create new sub-paths using LineTo (), ArcTo (), Quadraticcurveto (), and Beziercurveto (). Use the Beginpath () method every time you want to start drawing a path.
Canvas supports 3 lines of connection styles, including: miter, round, and bevel. Setting the connection style is set with the LineJoin property. By default, the miter style is used.
Some of the code examples above are as follows:
1 <! DOCTYPE html> 2 Linear gradientTo fill a graphic with a linear gradient effect, you first use the Createlineargradient () method to create a linear gradient object from the context object.
The four parameters of the Createlineargradient () method determine a virtual segment, and the gradient is along the direction of the line segment.
Then use the Addcolorstop method to set the color of the key points on the gradient line for the linear gradient object, offset to indicate where the key points are in the gradient virtual segment, and the value range of offset is 0 to 1, where 0 is the starting point, and 1 is the terminating point. A value between 0 and 1 represents a position in the middle of this virtual segment.
This linear gradient object is then assigned to the FillStyle property of the context object as a fill type. Canvas fills the shape based on the color variation of the key points on the gradient virtual segment.
Example code:
1 function Linear () {2 var canvas = document.getElementById ("MyCanvas"); 3 var context = Canvas . GetContext ("2d"); 4 5 var grd = context.createlineargradient (0, 0, 450, 400);//gradient path from (0,0) to (450,300) 6 7 8 Grd.ad Dcolorstop (0, "#000000"); 9 Grd.addcolorstop (0.5, "#ff0000"), Grd.addcolorstop (1, "#ffffff"), 11 12////View the gradient effect. //context.beginpath ();//context.fillstyle = Grd;15//context.fillrect (0, 0, 450, Context.beginpath () Context.moveto (170, 80);//starting at Context.beziercurvet O (130, 100, 130, 150, 230, 150);//Two control points, one endpoint (the starting point of the next path) Context.beziercurveto (250, 180, 320, 180, 340, 150); Context.beziercurveto (420, 430, 420, 30, 390, 370); Context.beziercurveto. 340, Context.beziercurveto (5, +, +, +), and Context.bezierCurveTo (5, 26 27//circumference), context.strokest, (+); YLE = "Blue"; context.linewidth = 15;30 Context.closepath (); Context.stroke (); 32 Filled Context.fillstyle = grd;34 context.fill (); 35 36}
Effect
Radial gradientA radial gradient is similar to a linear gradient except that the gradient direction is not a line segment but between two circles. Use the Createradialgradient () method to create a gradient object, which is the start and end circle of the gradient. Such as:
Context.createradialgradient (StartX, Starty, Startradius, EndX, EndY, Endradius);
Example code:
1 function Radial () {2 var canvas = document.getElementById ("MyCanvas"); 3 var context = Canvas . GetContext ("2d"); 4 Context.beginpath (); 5 6//Three note the effect is different, you can compare view 7//Note An example is plotted 8 Context.moveto (170, 80); 9 Context.beziercurveto (130, 100, 130, 150, 230, 150);//Two control points, one endpoint Context.beziercurveto (250, 1 ------------340, Context.beziercurveto (420, 390, 420, (); Context.beziercu Rveto (430, 5, 370, A, 340,), Context.beziercurveto (+------------------------) Context.bez Iercurveto (Max, 5, (), (+), (+), Context.closepath (); 16//Create radial Gradient object, var grd = Context.createradialgradient (238, 50, 10, 238, 50, 200);//Two Center + RADIUS 18//Set the color of the starting circle of the gradient Grd.addcolor Stop (0, "#FF0000"); 20//sets the color at which the gradient terminates the circle Grd.addcolorstop (1, "#00FF00"); 22 23///Note Two to see the gradient effect of//context.arc (238, 25, 0, Math.PI * 2, true);////concentric round effect////cont Ext.arc (238, 27, 0, Math.PI * 2, true);////non-concentric round effect//context.arc (238, $, 0, MATH.P I * 2, true); 29 30////Note Three pull the distance to see the effect of two circles//context.arc (+,, 0, Math.PI * 2, true); 32 Context.arc (0, Math.PI * 2, true); Context.strokestyle = "Blue"; 35 Context.linewidth = 2;36 Context.closepath (); Notoginseng Context.stroke (); Context.fillstyle = grd;39 Context.fill (); 40}
Effect
Drawing an imageThe DrawImage () method is required to draw the image. This method requires an image object and a starting point coordinate as an argument, where the starting point coordinates are relative to the upper-left corner of the canvas. Such as:
Context.drawimage (imageobj, x, y);
Since the DrawImage () method requires an Image object as an argument, we need to load the image before actually calling DrawImage (). This requirement can be achieved through the onload event of the image object. Note, however, that onload should assign values before specifying the image source with the SRC attribute of the image object.
Method DrawImage () can also accept Destwidth and destheight two parameters to display an image in any specified size:
Context.drawimage (imageobj, x, y, width, height);
Method DrawImage () can also add six additional parameters to achieve clipping of the image. These six parameters are, Sourcex,sourcey, Sourcewidth, Sourceheight, Destwidth and Destheight. These six parameters correspond to the meaning can be read. Context.drawimage (imageobj, SX, SY, SW, SH, dx, dy, DW, DH);
Picture Source (Https://developer.mozilla.org/zh-CN/docs/Web/Guide/HTML/Canvas_tutorial/Using_images#Using_images_which_ Are_on_the_same_page)
Example code:
1 function drawimg () {2 var canvas = document.getElementById ("MyCanvas"); 3 var context = Canvas.getcontext ("2d" ); 4 var img = new Image (); 5 //For image loading, add drawing method to its Load method 6 img.onload = function () {7 context.drawimage (img , 0, 200);//The original output is in position (0,300) 8 context.drawimage (IMG, 0, 0, 100, 100);//In position (0,0) The picture is (scaled) 100*100 9 Context.drawimage (IMG, 50, 50, 150, 150, 0, 120, 100, 130);//Crop the original image from the upper-left corner (50,50) to the lower-right corner (150,150) and zoom in position (0,120) to 100*130 's picture 10 One -to-one var pattern = Context.createpattern (img, "repeat"); Context.fillstyle = pattern;13 Context.fillrect (0, canvas.width-20, canvas.height-20);//Fill a rectangle with a }15 img.src = "http:// W3school.com.cn/i/ct_html5_canvas_image.gif ";
As follows:
Font, size, and style of textFriendly reminder: Here to introduce a little more text, you can first run the example, look at the effect and then look back to the introduction, then at a glance.
To set the font, size, and style, you need to use the Font property of the context object. The style can be normal, italic, or bold. The default is normal.
Context.font = ' italic 40px Calibri ';
The color of the text is set with the FillStyle property
To depict the effect of the font edge, use the Stroketext () method instead of Filltext () and replace the FillStyle property with the Strokestyle property. From QQ Group Daquan
The alignment feature of the text is set using the TextAlign property. The options available include start, end, left, center, and right. The aligned position is a vertical line relative to a virtual line, which is the text x position defined by Filltext () or Stroketext ().
The Textbaseline property is required to align the vertical. The options available for this property include: Top, Hanging,middle, alphabetic, ideographic, and bottom. By default, it is alphabetic.
To get the scale information about the text, you can use the Measuretext () method. This method requires a text string group as a parameter, and returns a scale object. The data in the scale object is based on the provided string parameters and the current text font information. Note: because the pixel height of the text is equal to the size of the font, the scale object returned from Measuretext () does not contain the height data. Such as:
var metrics = context.measuretext ("text");
var width = metrics.width;
The sample code is as follows:
1 <! DOCTYPE html> 2 Effect (due to LZ problem, the center of the setting is not centered in the diagram):
SummaryThis article describes lines, paths, gradients, and text, and the next chapter describes shadows, state storage, and recovery.
Because LZ is not as idle as before, may delay the progress, but I will try to persist in writing the series, thank you for your support.
HTML5 Simple Entry Series