Original: HTML5 new core Tool--canvas
The canvas element is the core of HTML5, an element that relies on JavaScript to draw ornate images.
The canvas is determined by the attribute definition in the HTML code of a drawing area to determine the height and width, and the JavaScript code can access the region, generating dynamic graphics with a complete set of drawing functions similar to other generic two-dimensional APIs.
Canvas can draw very ornate graphics in the browser, such as:
Of course, this should be a more advanced usage, this dish will not =.=
Canvas a big role is to make the game, this article through the Bo Master before a small game to introduce the use of canvas from zero, first show the following:
OK, this is the game done with canvas.
Before you draw the preparation work:
1. Add a canvas tag to the body, set its ID, width, height, and, of course, also dynamically set its width height.
<id= "MyCanvas" width= "$" height= "500" ></canvas>
2. Get the Canvas object context obj.getcontext (PAR), par parameter is "2d", currently canvas only supports two-dimensional effects.
var ctx = document.getElementById ("MyCanvas"). GetContext ("2d");
so you have a 1200*500 "canvas" and a paintbrush called "CTX", Next we'll start with some of the simplest graphs.
To draw a rectangle:
The sample code is as follows:
var ctx=document.getelementbyid ("container"). GetContext ("2d"); Ctx.fillstyle= "Blue"; Ctx.fillrect (10,10,200,100); Ctx.linewidth=10; Ctx.strokestyle= "Red"; Ctx.strokerect (300,10,200,100);
Where fill represents a fill, and a stroke indicates that only the bounding rectangle is drawn.
The same fillrect represents a solid rectangle, strokerect represents a rectangular border, and they all have four parameters: the x,y,w,h are horizontal, wide, and high.
FillStyle represents the fill style, and Strokestyle represents the border style.
The linewidth represents the line width.
Show Results:
It is important to note that setting styles should be written before drawing, otherwise the style will not render.
When drawing multiple shapes, you should draw the path before drawing a drawing, close the drawing path after customizing, and draw a drawing. For example, the standard notation for the above example should be:
var ctx=document.getelementbyid ("container"). GetContext ("2d"); Ctx.beginpath (); Ctx.fillstyle= "Blue"; Ctx.fillrect (10,10,200,100); Ctx.closepath (); Ctx.stroke (); Ctx.beginpath (); Ctx.linewidth=10; Ctx.strokestyle= "Red"; Ctx.strokerect (300,10,200,100); Ctx.closepath (); Ctx.stroke ();
Beginpath () Opens the drawing path, Closepath () closes the drawing path, and the stroke () draws the custom shape. Be sure to make a habit of the following exercises, otherwise when you draw a line you will find that the line is not connected due to an unclosed drawing path.
To draw a line:
The sample code is as follows:
var ctx=document.getelementbyid ("container"). GetContext ("2d"); Ctx.beginpath (); Ctx.moveto (400,100); Ctx.lineto (300,200); Ctx.lineto (350,200); Ctx.lineto (250,300); Ctx.lineto (400,300); Ctx.closepath (); Ctx.stroke ();
Where moveto indicates that the brush is moved to a coordinate, lineto refers to where to begin drawing the brush's placement. This time we want to draw a simple canopy, the result:
As we can see, we only draw half of it here. (400,100) The position is the tree top, (400,300) position is the middle of the tree bottom, the line auto-closing is the effect that we turn off the drawing path.
Next we finish drawing the other half and fill the tree with green:
var ctx=document.getelementbyid ("container"). GetContext ("2d"); Ctx.beginpath (); Ctx.fillstyle= "green"; Ctx.moveto (400,100); Ctx.lineto (300,200); Ctx.lineto (350,200); Ctx.lineto (250,300); Ctx.lineto (400,300); Ctx.lineto (550,300); Ctx.lineto (450,200); Ctx.lineto (500,200); Ctx.lineto (400,100); Ctx.fill (); Ctx.closepath (); Ctx.stroke ();
Note that the last fill () is the fill style:
Draw a circle:
Example code:
var ctx=document.getelementbyid ("container"). GetContext ("2d"); Ctx.beginpath (); Ctx.arc (200,200,100,0,360*math.pi/180,true); Ctx.closepath (); Ctx.stroke ();
Arc (x,y,r,starta,enda,anti); The parameters represent: center cross, ordinate, radius, starting angle (need to convert to radians), terminating angle, drawing direction.
Draw a circle with canvas, if you are just touching it must feel very tangled, because its parameters are many of the opposite. Here for everyone not tangled, I more wordy a few words.
The calculation of the starting and stopping angle is different from our mathematical angle calculation, the angle of mathematics is positive counterclockwise, and the starting and ending angle here is clockwise, that is, when you set the angle to 0 degrees, the stop angle is set to 120 degrees. It rotates the calculation angle from the right horizontal position downward.
There is also the drawing direction, true for counterclockwise, and false for clockwise. The faint of the classmate look at the following example:
Ctx.arc (200,200,100,0,120*math.pi/180,true);
Set the angle to 0, stop angle 120. The mathematical thought should be an arc less than the upper half of the semicircle, and the result:
This is true to draw counterclockwise, so the graph plotted is larger than the semicircle. If you change to false:
At this point, the drawing is less than half-circle, here you should also understand that arc angle calculation direction is the opposite of mathematics. Want to draw a small semicircle in the top? The stop angle is set to-120 degrees and the direction of the drawing is true.
Here wordy so much is to hope just contact friends less detours, not like we study half a day.
To draw a shadow:
var ctx=document.getelementbyid ("container"). GetContext ("2d"); Ctx.beginpath (); Ctx.fillstyle= "Gray"; Ctx.shadowoffsetx=5; Ctx.shadowoffsety=5; Ctx.shadowcolor= "Gold"; Ctx.shadowblur=5; Ctx.fillrect (10,10,100,100); Ctx.closepath (); Ctx.stroke ();
Shadowoffsetx, shadowoffsety represents the shadow horizontal, vertical offset, shadowcolor represents the shadow color, and Shadowblur represents the blur level.
Because before the CSS3 related blog post already told a lot about the shadow of things, here is a stroke. It is still important to note that the style is set first, and then the rectangle is drawn, and the effect is not rendered in reverse order.
To draw a gradient:
Linear gradient:
Ctx.beginpath (); var Color=ctx.createlineargradient (500,500,500,0); Color.addcolorstop (0.3, "orange"); Color.addcolorstop (0.5, "yellow"); Color.addcolorstop (1, "Gray"); Ctx.fillstyle=Color; Ctx.fillrect (0,0,1200,500); Ctx.closepath (); Ctx.stroke ();
By assigning Ctx.createlineargradient () to a color variable, the color variable can add multiple gradient colors, addcolorstop a total of two parameters, 1. Offset (0-1) 2. Color. Finally, assign the color variable to FillStyle.
Createlineargradient () has four parameters: 1, 2 for the starting face, 3, 4 for the last face.
Radial gradient:
Ctx.beginpath (); Ctx.arc (500,300,100,0,360*math.pi/180,true); var Color=ctx.createradialgradient (500,300,30,500,300,100); Color.addcolorstop (0, "Red"); Color.addcolorstop (0.5, "orange"); Color.addcolorstop (1, "yellow"); Ctx.fillstyle=Color; Ctx.fill (); Ctx.closepath (); Ctx.stroke ();
Similar to a linear gradient, the difference is that there are six parameters in the name Createradialgradient (): 1, 2. The center coordinate of the start circle of the gradient, 3. The radius of the start circle of the gradient, 4, 5. The center coordinate of the gradient end circle, 6. The radius of the end circle of the gradient.
Draw text:
Ctx.beginpath (); Ctx.strokestyle= "Gold"; Ctx.fillstyle= "Bule"; Ctx.font= "50px Microsoft Jas Black" ; Ctx.stroketext ("Hello world! ", 700,200); Ctx.font=" 30px young Circle "; Ctx.filltext (" Hello Kitty? ") ", 700,300); Ctx.fill (); Ctx.closepath (); Ctx.stroke () ;
Filltext (Text,x,y,[maxwidth]) draws a string, text indicates the text content, and x, y text coordinate position. [MaxWidth] Optional, set the maximum character wide to prevent overflow. Font to set fonts. Other parameters:textAlign Set Text horizontal alignment value is start|end|left|right|center default value is starttextbaseline Set Text vertical alignment value is top|hanging|middle|alphabetic|ideographic|bootom default is alphabeticEveryone is interested in trying it yourself.
Picture drawing:call ... Write a half-day finally wrote to the point, relative to the above simple graphic drawing, picture drawing to use more, especially in the game. here is an easier way to first write in body:
<div class= "Hide" > </div>
Add the image you want to draw into the body first, then hide the parent div, and a hidden div can put all the pictures in a project that need to be drawn or even an audio file, as if it were a library of objects unseen by others.
And then:
var ctx = document.getElementById ("MyCanvas"). GetContext ("2d"); var img=document.getelementbyid ("myimg"); Ctx.beginpath (); Ctx.drawimage (img,x,y); Ctx.closepath (); Ctx.stroke ();
Get the Picture object you want to draw and draw it through DrawImage. Here DrawImage () can have 3 parameters, 5 parameters, and 9 parameters.
3 parameters: 1. A picture object that needs to be drawn 2,3. Picture coordinates;
5 parameters: 1. The picture object that needs to be drawn 2,3. Picture coordinates 4,5. Picture width high;
9 parameters: 1. The picture object that needs to be drawn 2,3. To draw the horizontal longitudinal cutting point of the picture 4. Transverse cutting width 5. Cutting height 6,7. Cut the picture coordinates 8,9. Cut the picture width high.
The first two better understand, the third parameter mode how to use it? Here's an example: In the beginning of the game, The Walking monster is not gif, but the following background transparent PNG format:
We capture the different areas of the image through a certain interval of time, which is the effect of animation. When it comes to cutting pictures, people who have learned about Web performance optimization can easily think of spirite by bringing all the images they need on a webpage to a picture, and which part to intercept.
Far away, now we're trying to get this green monster to come up:
varCtx=document.getelementbyid ("container"). GetContext ("2d")); varImg=document.getelementbyid ("Myimg"); varX=0; varCountnum=0; functionPicrun () {Ctx.clearrect (0,0,1200,1000); Countnum++; if(countnum==10) {X+=129; Countnum=0; } if(x>=387) {X=0; } ctx.beginpath (); Ctx.drawimage (Img,x,0,129,135,100,100,129,135); Ctx.closepath (); Ctx.stroke (); } window.setinterval (Picrun,30);
First, add a picture to get the picture object. Analysis of the monster walk that picture, width of 515px, height of 135px, that is, each individual monster width of One-fourth is 129px, high for 135px.
The horizontal cut point is set to the variable x, as this figure requires no slitting, and the longitudinal cut point is set as a constant, in practice.
Fill in the parameters in the DrawImage, in this case only the horizontal cutting point is a variable. Loop through SetInterval to execute the Picrun function once every 30 milliseconds. Countnum commonly known as counter, in the game is more common, the purpose is to control the frequency of the image switching.
(Because a game usually has multiple objects with different action frequencies, it is certainly not possible to arbitrarily change the setinterval execution frequency.) By adding a counter, you can control the action frequency of each object very well.
In this example, the picture switching frequency is 30*10 300 milliseconds at a time, when switching the horizontal cutting point to the right 135px is the monster width, when the transverse cutting point is greater than 3 monster width back to 0 coordinate re-cutting.
Clearrect () is to clear the previous layer, always display only one picture, otherwise each cut out of the new graph will not stop superimposed.
Results: