Home > Web Front-end > H5 Tutorial > body text

HTML5 Canvas tag use collection_html5 tutorial skills

WBOY
Release: 2016-05-16 15:51:34
Original
1488 people have browsed it

1. Basic concepts

What is Canvas

is a new HTML element, which is defined in HTML5. This element can usually be used to draw graphics, synthesize images, etc. in HTML pages through JavaScript, and can also be used to do some animations. Of course, the HTML5 specification is still in the draft stage, and the official release may have to wait until 2010, but many browsers already support part of the HTML5 specification. Browsers that currently support the canvas element include Firefox 3, Safari 4, Chrome 2.0, etc. Therefore, when running the examples on this page, please make sure you are using one of the above browsers.

Although there are many tutorials about Canvas in Mozilla, I decided to record my learning process. If you feel that what I wrote is not clear enough, you can find a link to the Canvas tutorial on the Mozilla website in the references.

Also, you can find some interesting Canvas examples here

Get started with Canvas

Using Canvas is very 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 and does not perform any operations on it. At this time, the canvas element looks no different from the div element. Nothing on the page Can’t tell:)
In addition, the size of the canvas element can be specified through the width and height attributes, which is somewhat similar to the img element.

The core of Canvas: Context
As mentioned earlier, the Canvas object can be operated through JavaScript to draw graphics, synthesize images, etc. These operations are not performed through the Canvas object itself, but It is performed by obtaining the Canvas operation context through a method getContext of the Canvas object. In other words, when we use the Canvas object later, we will 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.
Getting the Context of the Canvas object is very simple. Just call the getContext method of the canvas element directly. When calling, you need to pass a Context type parameter. The only type value currently available and available is 2d:


The embarrassment of Firefox 3.0.x

Although Firefox 3.0.x supports the canvas element, it is not implemented in full compliance with the specification. The fillText and measureText methods in the specification are replaced by several Firefox-specific methods in Firefox 3.0.x. Therefore, in Firefox 3.0 When using Canvas in .x, you need to first fix the differences between these methods in different browsers.

The following code is taken from the Mozilla Bespin project, which corrects the inconsistency 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 does not support fillText and its related methods and properties of the Canvas object in the HTML5 specification.

Hello, Canvas!

After some preliminary understanding of Canvas, we started to write our first Canvas program, another branch of the famous HelloWorld "Hello, Canvas":


运行示例,Canvas 对象所在区域显示出“Hello, World!”,这正是代码中 ctx.fillText("Hello, World!", 20, 20); 的作用。

fillText 以及相关属性

fillText 方法用来在 Canvas 中显示文字,它可以接受四个参数,其中最后一个是可选的:

void fillText(in DOMString text, in float x, in float y, [Optional] in float maxWidth);

其中 maxWidth 表示显示文字时最大的宽度,可以防止文字溢出,不过我在测试中发现在 Firefox 与 Chomre 中指定了 maxWidth 时也没有任何效果。

在使用 fillText 方法之前,可以通过设置 Context 的 font 属性来调整显示文字的字体,在上面的示例中我使用了“20pt Arial”来作为显示文字的字体,你可以自己设置不同的值来看具体的效果。

二、路径

图形的基础 - 路径

在 Canvas 中,所有基本图形都是以路径为基础的,也就是说,我们在调用 2dContext 的 lineTo、rect 等方法时,其实就是往已经的 context 路径集合中再添加一些路径点,在最后使用 fill 或 stroke 方法进行绘制时,都是依据这些路径点来进行填充或画线。

在每次开始绘制路径前,都应该使用 context.beginPath() 方法来告诉 Context 对象开始绘制一个新的路径,否则接下来绘制的路径会与之前绘制的路径叠加,在填充或画边框时就会出现问题。在绘制完成路径后,可以直接使用 context.closePath() 方法来关闭路径,或者手动关闭路径。另外,如果在填充时路径没有关闭,那么 Context 会自动调用 closePath 方法将路径关闭。

基本路径方法

1. beginPath, closePath

这两个方法在前面已经介绍过,分别用来通知 Context 开始一个新的路径和关闭当前的路径。

在 Canvas 中使用路径时,应该要保持一个良好的习惯,每次开始绘制路径前都要调用一次 beginPath 方法,否则画出来的效果难看不说,还会严重影响性能。

在下面这张图中,左边的图形在每次绘制矩形前都调用了一次 beginPath 来清除之前的路径并重新开始绘制新的路径,而后面的图形则就只在绘制所有图形前调用了一次 beginPath 来清除路径,因此,虽然这里是使用的边框色是 #666,但是右边的图形颜色比左边的深一些,因为每次使用 stroke 绘制边框时,会把之前的路径再次绘制一遍,叠加起来颜色就比原来深一些。


When the number of paths in the Context is small, the performance is acceptable if the display effect is not considered. However, if the number of paths in the Context is large, beginPath is not used before starting to draw a new path, because each drawing will The previous path needs to be redrawn, and the performance will drop exponentially.

Therefore, Unless there are special needs, beginPath must be called to start a new path every time before starting to draw a path.


2. Movement and straight line moveTo, lineTo, rect



void moveTo(in float x, in float y);

When drawing a path in Canvas, it is generally not necessary to specify a starting point. The default starting point is the end point of the last drawn path. Therefore, if you need to specify a starting point, you need to use the moveTo method to specify the position to move to.

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 starting point of drawing inside the Context will move to the end point of the straight 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 upper left corner position, width and height through parameters. After calling rect , the drawing starting point of Context will move to the upper left corner of the rectangle drawn by rect .

The

rect method is a little different from the arc method to be introduced later and other path methods. They use parameters to specify the starting point, rather than using 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 instructions of the WHATWG document, this method is to draw an arc tangent to two rays. One of the two rays passes through the Context to draw the starting point and the end point is (x1, y1), and the other one passes through (x2, y2), the end point is (x1, y1), this arc is the smallest arc tangent to these two rays. After calling the arcTo method, add the tangent point between the arc and the ray (x1, y1)-(x2, y2) to the current path as the starting point for the next drawing.

In testing, it was found that Firefox and Opera currently do not support this method well, and only Chrome and Safari 4 can draw the correct path.


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, specifying the position and size of the arc through the center position, starting radian, and ending radian. This method also does not depend on the drawing starting point maintained by Context. The direction of rotation when drawing an arc is specified by the last parameter anticlockwise. If it is true, it is counterclockwise, and if it is false, it is clockwise.

void quadraticCurveTo(in float cpx, in float cpy, in float x, in float y);

The quadraticCurveTo method is used to draw a quadratic spline path. The parameters cpx and cpy specify the position of the control point, x and y specify the position 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 a Bezier curve path. It is similar to quadraticCurveTo, but the Bezier curve has two control points, so the cp1x, cp1y, cp2x, cp2y in the parameters are used to specify the positions of the two control points. , while x and y specify the position of the tuft.


4. fill, stroke, clip

The two methods 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 clipping area for Canvas. The code after calling the clip method is only valid for this set clipping area and will not affect other places. This method is very useful when performing local updates. By default, the clipping area is a rectangle with the upper left corner at (0, 0) and a width and height equal to the width and height of the Canvas element respectively.

When drawing this picture, although fillRect(0, 0, 100, 100) was used twice to fill a 100x100 rectangle, the displayed result is that only a small area in the middle was filled the second time. This is because the clip method is used to set the clipping area between two fillings, so that the second filling will only affect the small area in the middle.


5. clearRect, fillRect, strokeRect

These three methods are not path methods, but are used to directly process the content on the Canvas, which is equivalent to the background of the Canvas. Calling these three methods will not affect the starting point of the Context drawing.

When you want to clear all the content on the 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 of the same size as the Canvas and then use the fill method. Go clear.

Conclusion

Through the path method of Canvas, you can use Canvas to process some simple vector graphics, so that they will not be distorted when scaling. However, the path method of Canvas is not very powerful, at least it does not even have an elliptical path...

References
1. The Canvas Element, WHATWG

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template