In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article shows you how HTML5 Canvas tags are used and included, the content is concise and easy to understand, it can definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
I. basic concepts
What is Canvas?
Is a new HTML element that is defined in HTML5. This element can usually be used in HTML pages to draw graphics, composite images, and so on through JavaScript, and can also be used to do some animation. Of course, the HTML5 specification is still in the draft stage, and the official release may not be until 2010, but many browsers already support some of the HTML5 specification. Currently, browsers that support canvas elements include Firefox 3 +, Safari 4, Chrome 2.0 +, etc., so make sure you are using one of these browsers when running the examples on this page.
Although there are many tutorials on Canvas in Mozilla, I decided to document my learning process. If you think I'm not clear enough, you can find a link to the Canvas tutorial on the Mozilla website in Resources.
In addition, you can find some interesting Canvas examples here
Start using Canvas
Using Canvas is simple, just like using other HTML elements, you only need to add a tag to the page:
The code is as follows:
Of course, this simply creates a Canvas object without doing anything with it. At this time, the canvas element looks no different from the div element, and nothing can be seen on the page:)
In addition, the size of the canvas element can be specified by the width and height attributes, which is somewhat similar to the img element.
The core of Canvas: Context
It was mentioned earlier that you can use JavaScript to manipulate Canvas objects to draw graphics, synthesize images, and so on. These operations are not done through the Canvas object itself, but through a method of the Canvas object, getContext, to obtain the Canvas operation context. In other words, when we use the Canvas object later, we deal with the Context of the Canvas object, and the Canvas object itself can be used to obtain information such as the size of the Canvas object.
To get the Context of a Canvas object, you can simply call the getContext method of the canvas element. When you call it, you need to pass a Context type parameter. Currently, the only type value available is 2d:
Var canvas = document.getElementById ("screen")
Var ctx = canvas.getContext ("2d")
Embarrassment of Firefox 3.0.x
Although Firefox 3.0.x supports the canvas element, it is not fully implemented in accordance with the specification. The fillText and measureText methods in the specification are replaced by several Firefox-specific methods in Firefox 3.0.x, so when using Canvas in Firefox 3.0.x, you need to first fix the differences of these methods in different browsers.
The following code, taken from the Mozilla Bespin project, fixes inconsistencies between the Context object of Canvas in Firefox 3.0.x and the HTML5 specification:
Function fixContext (ctx) {
/ / * upgrade Firefox 3.0.x text rendering to HTML 5 standard
If (! ctx.fillText & & ctx.mozDrawText) {
Ctx.fillText = function (textToDraw, x, y, maxWidth) {
Ctx.translate (x, y)
Ctx.mozTextStyle = ctx.font
Ctx.mozDrawText (textToDraw)
Ctx.translate (- x,-y)
}
}
/ / * Setup measureText
If (! ctx.measureText & & ctx.mozMeasureText) {
Ctx.measureText = function (text) {
If (ctx.font) ctx.mozTextStyle = ctx.font
Var width = ctx.mozMeasureText (text)
Return {width: width}
}
}
/ / * Setup html5MeasureText
If (ctx.measureText & &! ctx.html5MeasureText) {
Ctx.html5MeasureText = ctx.measureText
Ctx.measureText = function (text) {
Var textMetrics = ctx.html5MeasureText (text)
/ / fake it 'til you make it
TextMetrics.ascent = ctx.html5MeasureText ("m") .width
Return textMetrics
}
}
/ / * for other browsers, no-op away
If (! ctx.fillText) {
Ctx.fillText = function () {}
}
If (! ctx.measureText) {
Ctx.measureText = function () {return 10;}
}
Return ctx
}
Note: as of Opera 9.5, Opera did not support the fillText of Canvas objects and their related methods and properties in the HTML5 specification.
Hello, Canvas!
After some preliminary understanding of Canvas, let's start writing our first Canvas program, another branch of the famous HelloWorld, "Hello, Canvas":
(function () {
Var canvas = document.getElementById ("screen")
Var ctx = fixContext (canvas.getContext ("2d"))
Ctx.font = "20pt Arial"
Ctx.fillText ("Hello, Canvas!", 20,20)
Ctx.fillText ("www.xujiwei.com", 20,50)
Function fixContext (ctx) {
/ / * upgrade Firefox 3.0.x text rendering to HTML 5 standard
If (! ctx.fillText & & ctx.mozDrawText) {
Ctx.fillText = function (textToDraw, x, y, maxWidth) {
Ctx.translate (x, y)
Ctx.mozTextStyle = ctx.font
Ctx.mozDrawText (textToDraw)
Ctx.translate (- x,-y)
}
}
/ / * Setup measureText
If (! ctx.measureText & & ctx.mozMeasureText) {
Ctx.measureText = function (text) {
If (ctx.font) ctx.mozTextStyle = ctx.font
Var width = ctx.mozMeasureText (text)
Return {width: width}
}
}
/ / * Setup html5MeasureText
If (ctx.measureText & &! ctx.html5MeasureText) {
Ctx.html5MeasureText = ctx.measureText
Ctx.measureText = function (text) {
Var textMetrics = ctx.html5MeasureText (text)
/ / fake it 'til you make it
TextMetrics.ascent = ctx.html5MeasureText ("m") .width
Return textMetrics
}
}
/ / * for other browsers, no-op away
If (! ctx.fillText) {
Ctx.fillText = function () {}
}
If (! ctx.measureText) {
Ctx.measureText = function () {return 10;}
}
Return ctx
}
) ()
Running the example shows "Hello, World!" in the area where the Canvas object is located, which is what ctx.fillText ("Hello, World!", 20,20); does in the code.
FillText and related properties
The fillText method, which is used to display text in Canvas, accepts four parameters, the last of which is optional:
Void fillText (in DOMString text, in float x, in float y, [Optional] in float maxWidth)
Where maxWidth represents the maximum width when displaying text, which prevents text overflow, but I found that specifying maxWidth in Firefox and Chomre had no effect.
Before using the fillText method, you can adjust the font of the display text by setting the font property of Context. In the above example, I used "20pt Arial" as the font of the display text. You can set different values to see the specific effect.
2. Path
The basis of the drawing-path
In Canvas, all the basic graphics are based on the path, that is to say, when we call 2dContext's lineTo, rect and other methods, we actually add some path points to the existing context path set, and when we finally use the fill or stroke method to draw, we fill or draw lines according to these path points.
Before each time you start drawing a path, you should use the context.beginPath () method to tell the Context object to start drawing a new path, otherwise the next path will be superimposed with the previously drawn path, and there will be problems when filling or drawing borders. After the path is drawn, you can use the context.closePath () method directly to close the path, or you can close the path manually. In addition, if the path is not closed when populated, Context automatically calls the closePath method to close the path.
Basic path method
1. BeginPath, closePath
These two methods, described earlier, are used to tell Context to start a new path and close the current path, respectively.
When using paths in Canvas, you should maintain a good habit of calling the beginPath method every time before you start drawing the path, otherwise the effect of the drawing will be ugly and will seriously affect performance.
In the following figure, the figure on the left calls beginPath once before drawing the rectangle to clear the previous path and start drawing the new path again, while the latter graphic calls beginPath to clear the path only once before drawing all the graphics, so although the border color used here is # 666, the shape on the right is darker than the one on the left, because each time you use stroke to draw the border The previous path will be drawn again, and the color will be darker than the original.
Var canvas = document.getElementById ("canvas")
Var ctx = canvas.getContext ("2d")
Ctx.strokeStyle = "# 666"
Function useBeginPath () {
For (var I = 0; I
< 5; ++i) { ctx.beginPath(); ctx.rect(10 + i*20, 10 + i*20, 210 - i*40, 210 - i*40); ctx.stroke(); } } function notUseBeginPath() { ctx.beginPath(); for (var i = 0; i < 5; ++i) { ctx.rect(240 + i*20, 10 + i*20, 210 - i*40, 210 - i*40); ctx.stroke(); } } useBeginPath(); notUseBeginPath(); 在 Context 中路径数较少时,如果不考虑显示效果,性能上还可以接受,但是如果 Context 中的路径数很多时,在开始绘制新路径前不使用 beginPath 的话,因为每次绘制都要将之前的路径重新绘制一遍,这时性能会以指数下降。 因此,除非有特殊需要,每次开始绘制路径前都要调用 beginPath 来开始新路径。 2. 移动与直线 moveTo, lineTo, rectVar canvas = document.getElementById ("canvas")
Var ctx = canvas.getContext ("2d")
Ctx.beginPath ()
Ctx.moveTo (10,10)
Ctx.lineTo (110110)
Ctx.lineTo (10,110)
Ctx.lineTo (10,10)
Ctx.stroke ()
Ctx.beginPath ()
Ctx.rect (120,10,100,100)
Ctx.stroke ()
Void moveTo (in float x, in float y)
When you draw a path in Canvas, you generally do not need to specify a starting point, and the default starting point is the end of the last drawn path, so if you need to specify a starting point, you need to use the moveTo method to specify the location to which you want to move.
Void lineTo (in float x, in float y)
The lineTo method draws a direct path to the specified location. After calling the lineTo method, the drawing start point inside the Context moves to the end of the line.
Void rect (in float x, in float y, in float w, in float h)
The rect method is used to draw a rectangular path, specifying the location of the upper-left corner as well as width and height through parameters. After you call rect, the drawing starting point of Context moves to the upper-left corner of the rectangle drawn by rect.
The rect method is a little different from the arc method described later in that they specify the starting point using parameters rather than the starting point maintained internally by Context.
3. Curve arcTo, arc, quadraticCurveTo, bezierCurveTo
Void arcTo (in float x1, in float y1, in float x2, in float y2, in float radius)
According to the WHATWG documentation, this method is to draw an arc tangent to two rays, one of which is to draw the starting point (x1, y1) through the Context, and the other to pass through (x2, y2), with the end point (x1, y1). This arc is the smallest arc tangent to the two rays. After calling the arcTo method, add the tangent points of arcs and rays (x1, y1)-(x2, y2) to the current path as the starting point for the next drawing.
In the test, it is found that Firefox and Opera currently do not support this method well, and only Chrome and Safari 4 can draw the correct path.
Var canvas = document.getElementById ("canvas")
Var ctx = canvas.getContext ("2d")
Ctx.beginPath ()
Ctx.strokeStyle = "# 000"
Ctx.translate (200,200)
Ctx.moveTo (10,10)
Ctx.arcTo (110,60,10,110,30)
Ctx.stroke ()
Ctx.beginPath ()
Ctx.strokeStyle = "# 999"
Ctx.moveTo (10,6)
Ctx.lineTo (114,60)
Ctx.lineTo (10,114)
Ctx.stroke ()
Void arc (in float x, in float y, in float radius, in float startAngle, in float endAngle, in boolean anticlockwise)
The arc method is used to draw an arc path, and the location and size of the arc are specified by the position of the center, the starting Radian and the ending Radian, and this method does not depend on the starting point of Context maintenance. The direction of rotation when drawing an arc is specified by the last parameter, anticlockwise. If true is counterclockwise, false is clockwise.
Void quadraticCurveTo (in float cpx, in float cpy, in float x, in float y)
The quadraticCurveTo method is used to draw the quadratic spline path. In the parameters, cpx and cpy specify the position of the control point, x and y specify the location of the end point, and the starting point is the drawing starting point maintained by Context.
Void bezierCurveTo (in float cp1x, in float cp1y, in float cp2x, in float cp2y, in float x, in float y)
The bezierCurveTo method is used to draw the path of the Bezier curve, which is similar to quadraticCurveTo, but the Bezier curve has two control points, so the cp1x, cp1y, cp2x and cp2y in the parameters are used to specify the position of the two control points, while x and y specify the position of the grain.
Var canvas = document.getElementById ("canvas")
Var ctx = canvas.getContext ("2d")
Ctx.translate (10,10)
Ctx.beginPath ()
Ctx.arc (50,50,50,0, Math.PI, true)
Ctx.stroke ()
/ / quadraticCurveTo
Ctx.beginPath ()
Ctx.strokeStyle = "# 000"
Ctx.moveTo (110,50)
Ctx.quadraticCurveTo (160,0,210,50)
Ctx.stroke ()
Ctx.beginPath ()
Ctx.strokeStyle = "red"
Ctx.moveTo (110,50)
Ctx.lineTo (160,0)
Ctx.lineTo (210,50)
Ctx.stroke ()
/ / bezierCurveTo
Ctx.beginPath ()
Ctx.strokeStyle = "# 000"
Ctx.moveTo (220, 50)
Ctx.bezierCurveTo (250,0,280,10,320,50)
Ctx.stroke ()
Ctx.beginPath ()
Ctx.strokeStyle = "red"
Ctx.moveTo (220, 50)
Ctx.lineTo (250,0)
Ctx.lineTo (280,10)
Ctx.lineTo (320,50)
Ctx.stroke ()
4. Fill, stroke, clip
Fill and stroke are easy to understand and are used to fill paths and draw path lines, respectively.
The clip method is used to set a clip region for Canvas. The code after calling the clip method is only valid for this set clip region and does not affect anything else. This method is useful when you want to make a local update. By default, the clip region is a rectangle with the upper-left corner at (0,0) and the width and height equal to the width and height of the Canvas element, respectively.
When drawing this picture, although a 100x100-sized rectangle is filled with fillRect (0,0,100,100) twice, the result displayed is that the second filling is only a small piece in the middle, this is because the clip region is set by using the clip method between the two fills, so that the second filling will only affect the set middle part of the area.
Var canvas = document.getElementById ("canvas")
Var ctx = canvas.getContext ("2d")
Ctx.translate (10,10)
/ / fill a green rectangle
Ctx.fillStyle = "green"
Ctx.fillRect (0,0,100,100)
/ / set the clipping region
Ctx.beginPath ()
Ctx.rect (30,30,40,40)
Ctx.clip ()
Ctx.stroke ()
/ / fill a yellow rectangle
Ctx.fillStyle = "yellow"
Ctx.fillRect (0,0,100,100)
5. ClearRect, fillRect, strokeRect
These three methods are not path methods, but are used to deal with the content on Canvas directly, which is equivalent to the background of Canvas. Calling these three methods will not affect the starting point of Context drawing.
When you want to clear everything on Canvas, you can directly call context.clearRect (0,0, width, height) to clear it directly, instead of using the path method to draw a rectangular path the same size as Canvas and then using the fill method to clear it.
With the path method of Canvas, you can use Canvas to deal with some simple vector graphics without distortion when zooming. However, the path method of Canvas is not very powerful, at least there is no path with an ellipse.
The above content is how HTML5 Canvas tags are used and included. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.