<canvas> is a new element of HTML5, and you can use JavaScript scripts to draw graphics. For example: paint, synthesize photos, create animations and even real-time video processing and rendering.
compatibility , in addition to some of the IE6, IE7, IE8, and so on, most modern browsers can support.
I. Properties and Methods
1) Properties
<canvas> looks like the element, and the only difference is that it doesn't have the SRC and ALT attributes. In fact, the,<canvas> tag has only two attributes- width and height.
<id= "Strick" width= "Max" height= "Max" ></canvas>
There are some default properties, ID, style, etc.
2) method
1. getcontext(in domstring ContextID)
The canvas was initially blank. To demonstrate, the script first needs to find the render context and then draw it on top of it. This method is used to obtain the rendering context and its painting function.
The optional parameters in ContextType are "2d", "WebGL", "Webgl2", "Bitmaprenderer".
If it is "2d", the canvasrenderingcontext2d object is returned. If it is "WebGL," the webglrenderingcontext object is returned.
The ContextAttributes property will require different parameters depending on "2d" or "WebGL".
var canvas = document.getElementById (' Strick '); var ctx = Canvas.getcontext (' 2d ');
2. Todataurl(in optional domstring type, with any ... args)
Returns a data:url that encodes the picture in the canvas as a string, with multiple formats selected, and the default value of the type parameter is image/png.
Once did a picture synthesis function, has used this function. Notice a " canvas pollution " here.
Is that the embedded picture is cross-domain, then this method cannot be used. A simple analysis of preview, rotation, composition .
3. Toblob(in Function callback, in optional domstring type, in any ... args)
Returns a Blob(Binary large object). A blob represents a binary data, which is a class file object that contains read-only raw data.
In the " Mobile image operation (a)--upload " has done a brief introduction.
Second, draw 2D graphics
The 2D graphic is drawn here, and the properties or methods in the canvasrenderingcontext2d object are used.
On the MDN there is a basic tutorial "Canvas Tutorial ", covering a pretty full coverage.
1) Coordinate space
The starting point of the canvas is the upper-left corner, which can be customized by means of translate , such as rotation and scaling.
As shown, the canvas's axis is the opposite of the normal axis.
So clockwise is positive and counter-clockwise is negative.
2) Drawing shapes
The rectangle is the only native graphic drawing supported by the canvas. To draw a different shape, you need to draw a path to achieve it. The draw rectangle provides 3 methods .
A path is a collection of points that are formed by connecting segments or curves of different colors and widths. There are methods for manipulating paths and drawing paths (including Bezier curves) .
The operation process is roughly 4 steps, first create the path starting point, then draw the path, then close the path, and finally fill.
1. Simple graphics
is a few simple graphics, two triangles have a rotation of the canvas, counter-clockwise to draw the half-circle, three circles and a semi-circle of the smiley face, with a Bezier curve drawn by the dialogue bubble, you can debug the following effect online .
2. Complex graphics
In CSS, the border, font and so on can be set width, size, color, etc., advanced points also have shadows, gradients, Rgba and so on.
There are also actions in the canvas that draw text , linetype , text Styles , fill and stroke styles , gradients and Patterns , and shadows .
There are netizens painted the head of the gray wolf, very lifelike, can be online debugging , through the View source code, which is used in Beginpath, MoveTo, Quadraticcurveto and other path-related methods or properties.
3) Use picture
Canvas can be used to synthesize , scale , crop , rotate , deform , and manipulate images.
A. Simple synthesis
Now some websites will let you DIY do Zhang Hai newspaper, and then share to friends Circle. Some time ago made a simple poster, just to combine the pictures together, do not do graffiti and other operations, detailed introduction can see the " Mobile image Operation series "
B. Synthesis of advanced points
Advanced point of production posters , the ability to enter custom text, using the above mentioned in the drawing of the concept of the shape, when looking at the source code, found reference to the script "Hidpi-canvas-polyfill", to solve the canvas Blur the picture under the HD screen.
|
|
Simple synthesis |
Advanced compositing |
In addition to the basic operations, there are advanced pixel operations , get the rgba of a pixel in the picture, and then modify the values of R, G, B, or a in it to modify the color or transparency.
For example, mouse movement to get the RGBA value, color photo into black and white, mosaic and so on.
The first picture is to get the pixel value, and the second picture is grayed out.
In addition to manipulating images, canvas can manipulate video, also known as <video> tags.
4) Transformation matrix
The transform in CSS3 has a matrix concept, such as rotation, translation, warping, scaling, etc., which can be realized by matrix. About CSS3 Animation can refer to "CSS3 in the animation effect record "
There is a rotate() method in the canvas that implements rotation, but the canvas is actually rotated, not the one that rotates the drawing.
If you use the transform() method, you can implement a rotated shape. Here is a comparison example, can be debugged online .
The context matrix for the rendering is as follows, and the last line can be ignored:
The coordinates of the three-dimensional rendering are calculated as follows, the calculation process can be studied under linear algebra, the simple point is a and X, Y, 1, respectively, multiply.
The matrix calculation of rotate and skew involves the sine, cosine, and tangent of trigonometric functions .
// The matrix corresponding to scale () is written in CSS3, and the corresponding method is Canvasrenderingcontext2d.transformmatrix (sx,0,0,sy,0,0); /* SX and Sy correspond to the scaling ratios of the x and Y axes, respectively */ // rotate () the corresponding matrix // in JS, θ corresponds to a radian conversion formula of radians = 2 * pi/360 * angle matrix (cosθ,sinθ,-sinθ,cosθ,0,0); // skew () the corresponding matrix //θy corresponds to the y-axis of radians θx corresponds to the x-axis of radians matrix (1,tan (Θy), tan (θx), 1,0,0)
Matrix computing will also involve a lot of other mathematical knowledge, such as a function , I have basically forgotten, embarrassed, have to re-check.
There is an online editing matrix website that can be produced online .
5) Related calculation formulas
A. Basic formula for trigonometric functions
There are two inverse tangent functions in JavaScript,Math.atan(ratio) and math.atan2(y, x).
The first method returns a value between-PI/2 and PI/2 radians, and the second method returns a value between-pi and pi.
B. Reciprocal rotation of angles and radians
In JavaScript, trigonometric functions are used in radians, such as Math.sin, Math.Cos, and so on, and rotation is by angle. So there is a need for conversion between the two.
Radians is radian, degrees is angle
C. Distance between two points
The Pythagorean theorem of right triangle was used. The P1 and P2 in the axes are equivalent to A and B in the formula.
Third, canvas animation
To implement animation, you need to implement many physics concepts with JavaScript.
You can refer to the two books, "HTML5 JavaScript Animation Basics " and "HTML5 Canvas Basic Tutorial " for canvas animations. Both the PDF and the source have been shared.
1) Speed vector
Speed is part of the velocity vector (velocity) and the velocity vector also includes the direction.
The velocity vectors on the x-axis are represented by VX, with vy representing the velocity vectors on the y-axis. can also represent angular rotation, expressed in VR.
VX is a positive number to the right and negative to the left. VY is a positive number indicating downward, and a negative number indicates upward.
is a right to move the ball, Vx=1, detailed code can refer to here .
2) Angular velocity
Assuming that the object moves at a speed of 1 pixels to 45°, VX and VY can be obtained by cosine and sine.
Speed and direction are mapped into a right triangle.
VX = Math.Cos (angle) *speed;
VY = Math.sin (angle) *speed;
is an example of the angular velocity after calculation.
3) Acceleration
The velocity vector changes the physical position of the object, and the acceleration changes the velocity vector.
The picture below is the same as the GIF content in the speed vector, except that each loop adds 0.1 values to VX.
4) Border
Processing boundaries, there are many options, to remove, put back within the boundaries, screen wrapping, bounce back to the boundary, and so on.
The left image is the set back boundary, and the right image is the effect that bounces back to the boundary.
5) Friction
A relatively simple implementation is to set a friction (friction variable, a number less than 1), multiply this number with VX and VY, and get a new value.
These two values will become smaller and eventually stop.
In addition to the above several basic animation, there are some advanced animation, easing, bouncing, collision detection and so on.
Iv. advantages and disadvantages of canvas
1) Advantages:
1. When rendering images, text, and animations, because canvas does not have the overhead associated with parsing HTML and maintaining a hierarchical document model, these tasks are always faster in the canvas than in HTML.
2. A consistent, cross-platform rendering can be achieved. For example, the browser's Transform property, different browsers may need to use their own unique prefix.
3. The drawing can be saved directly as a. png or. jpg graphic.
4. Ideal for drawing raster images (such as games and irregular geometries), editing pictures, and other pixel-based graphics operations.
2) Disadvantages:
1. Since there is no DOM node in the canvas, it can only be judged by coordinates when an element needs to perform an interactive event (such as Click).
2. There is no API for animating, you must rely on timers and other events to update the canvas.
3. Rendering support for text is relatively poor, such as wrapping. There is no concept of hyperlinks in the canvas.
4. Because the text that is displayed programmatically on the canvas is actually a bitmap, the search crawler completely ignores the text. Text content cannot be recognized by screen readers.
So that you can use canvas