Eight core HTML5 Canvas technologies and their API usage, html5canvas

Source: Internet
Author: User

Eight core HTML5 Canvas technologies and their API usage, html5canvas

What is canvas?

The Canvas element is a part of HTML5 and allows the scripting language to dynamically render bitmap images. Canvas defines the height and width by the attribute in the HTML code of a printable area (NOTE: When setting the width and height with its attribute width and height, it cannot be "px" with the pixel unit "). JavaScript code can access this area and generate dynamic graphs using a complete set of drawing functions similar to other common 2D APIs.

CanvasEight core technologies (insights from Ohad Eder-Pressman, founder and CEO of 3D3R ):

1.Games

HTML5 is more three-dimensional and sophisticated in Web-based image display than Flash, Ohad (founder and CEO of 3D3R, Ohad Eder-Pressman) it is believed that the image produced using Canvas can make HTML5 games play a greater potential in smoothness and across products. Therefore, games play an important role in the HTML5 field.

2.Chart Creation

Chart creation is often ignored, but communication and cooperation between enterprises are inseparable from charts. Currently, some developers use HTML/CSS to create icons. However, Ohad thinks that you can use Canvas to create icons. In addition, it is good to use SVG (Scalable Vector Graphics) to create charts.

3. bannerAdvertisement

Flash has never appeared in a brilliant age. In the current and future smart phone era, HTML5 technology can play a huge role in banner advertising, and it is no longer appropriate to use Canvas to achieve dynamic advertising effects.

4.Simulator

Ohad believes that, in terms of visual effects and core functions, the simulator product can be fully implemented using JavaScript.

5.Remote Computer Control

Canvas allows developers to better implement Web-based data transmission and build a perfect visual interface.

6.Font Design

Custom rendering of fonts can be fully implemented based on Web and HTML5 technology.

7.Graphic editor

Ohad predicts that the graphic editor can be 100% Web-based.

8.Other content that can be embedded into the website

Similar to charts, audios, and videos, there are many elements that can better integrate with the Web without any plug-ins.

Canvas APIUsage:

Before use, you must create a canvas webpage element.

<Canvas height = "200" id = "myCanvas" width = "400"> canvas is not supported in your browser! </Canvas> <! -- If the browser does not support this API, the text in the middle of the canvas tag is displayed-"Your browser does not support canvas !". -->

Each canvas element has a corresponding context object, which is defined by the Canvas API. Therefore, you need to obtain this object by using the getContext method.

Var canvas = document. getElementById ('mycanvas '); if (canvas. getContext) {var ctx = canvas. getContext ('2d ');} // The getContext method specifies the parameter 2d, indicating that the canvas object is used to generate a 2d pattern (that is, a plane pattern ). If the parameter is 3d, it indicates that it is used to generate a 3D image (that is, a three-dimensional image). This part is actually called WebGL API (see other Articles of the blogger ).

 

The canvas provides a flat space for plotting. each point of the space has its own coordinate, x indicates the horizontal coordinate, and y indicates the vertical coordinate. The origin (0, 0) is located in the upper left corner of the image. The positive direction of the X axis is the right of the origin, and the positive direction of the Y axis is the downward direction of the origin.

Draw path

The beginPath method indicates the start of Line Painting. The moveTo (x, y) method sets the start point of a line segment. The lineTo (x, y) method sets the end point of a line segment. The stroke method is used to color a transparent line segment.

Ctx. beginPath (); // start to draw ctx. moveTo (20, 20); // set the path start point. The coordinates are (20, 20) ctx. lineTo (200, 20); // draw a straight line ctx to (, 20. lineWidth = 1.0; // set the lineWidth of ctx. strokeStyle = # CC0000; // sets the line color ctx. stroke (); // color the line. Then the entire line is visible. // The moveto and lineto methods can be used multiple times. Finally, you can use the closePath method to automatically draw a straight line from the current point to the start point to form a closed image, saving the use of the lineto method once.

Draw a rectangle

The fillRect (x, y, width, height) method is used to draw a rectangle. Its four parameters are the x coordinate and y coordinate of the vertex in the upper left corner of the rectangle, and the width and height of the rectangle. The fillStyle attribute is used to set the fill color of the rectangle.

Ctx. fillStyle = 'yellow'; ctx. fillRect (50, 50,200,100); // The strokeRect method is similar to fillRect for drawing hollow rectangles. Ctx. strokeRect (200,100,); // The clearRect method is used to clear the content of a rectangular area. Ctx. clearRect (100,50, 50,50 );

Draw text

FillText (string, x, y) is used to draw text. Its three parameters are the text content, the x coordinate of the start point, and the y coordinate. Before use, you must use font to set the font, size, and style (similar to the font attribute of CSS ). Similarly, the strokeText method is used to add hollow words.

// Set the font ctx. font = Bold 20px Arial; // sets the alignment mode ctx. textAlign = left; // sets the fill color ctx. fillStyle = #008600; // set the font content and position ctx on the canvas. fillText (Hello !, 10, 50); // draw the hollow word ctx. strokeText (Hello !, 10,100); // The fillText method does not support text line breaking, that is, all text appears in a row. Therefore, to generate multiple lines of text, you must call the fillText method multiple times.

Draw circles and slices

The arc method is used to draw slices.

Ctx. arc (x, y, radius, startAngle, endAngle, anticlockwise );

// The x and y parameters of the arc method are the Center Coordinate, radius is the radius, and startAngle and endAngle are the start angle and end angle of the slice (expressed in radians )//, anticlockwise indicates whether to draw (true) or clockwise (false) counterclockwise during graph creation)

// Draw a solid circular ctx. beginPath (); ctx. arc (60, 60, 50, 0, Math. PI * 2, true); ctx. fillStyle = #000000; ctx. fill (); // draw a hollow circular ctx. beginPath (); ctx. arc (60, 60, 50, 0, Math. PI * 2, true); ctx. lineWidth = 1.0; ctx. strokeStyle = #000; ctx. stroke ();

 Set gradient

The createLinearGradient method is used to set gradient.

Var myGradient = ctx. createLinearGradient (0, 0, 0,160); myGradient. addColorStop (0, # BABABA); myGradient. addColorStop (1, #636363); // the parameters of the createLinearGradient method are (x1, y1, x2, y2), where x1 and y1 are the start coordinate, and x2 and y2 are the end coordinate. With different coordinate values, you can generate a gradient from top to bottom, from left to right, etc. ctx. fillStyle = myGradient; ctx. fillRect (200,100 );

Set shadow

A series of shadow-related methods can be used to set shadows.

Ctx. shadowOffsetX = 10; // sets the horizontal displacement ctx. shadowOffsetY = 10; // sets the vertical displacement ctx. shadowBlur = 5; // sets the Blur ctx. shadowColor = rgba (0.5, 0,); // sets the shadow color ctx. fillStyle = # CC0000; ctx. fillRect (10, 10, 200,100); // canvas allows you to insert an image file into the canvas. You can use the drawImage method to re-paint the image after reading the image. Var img = new Image (); img. src = image.png; ctx. drawImage (img, 0, 0); // sets the corresponding image object and its position on the canvas. // it takes time to load the image, the drawImage method can only be called after the image is fully loaded. Therefore, the above code needs to be rewritten. Var image = new Image (); image. onload = function () {if (image. width! = Canvas. width) canvas. width = image. width; if (image. height! = Canvas. height) canvas. height = image. height; ctx. clearRect (0, 0, canvas. width, canvas. height); ctx. drawImage (image, 0, 0);} image. src = image.png; // The drawImage () method accepts three parameters. The first parameter is the DOM element (img tag) of the image file ), the second and third parameters are the coordinates of the upper left corner of the image in the // Canvas Element. (0, 0) in the preceding example indicates that the upper left corner of the image is placed in the upper left corner of the Canvas element. // The getImageData method can be used to read the Canvas content and return an object containing the information of each pixel. Var imageData = context. getImageData (0, 0, canvas. width, canvas. height); // The imageData object has a data attribute whose value is a one-dimensional array. The values of this array are the values of the red, green, blue, and alpha channels of each pixel in sequence, because // the length of this array is equal to the pixel width of the image x the pixel height of the image x 4, the range of each value is 0-255. This array is not only readable but also writable. Therefore, you can operate the image by operating on the value of this array. After modifying this array, use the putImageData method to re-paint the array content on the Canvas. Context. putImageData (imageData, 0, 0); // After modifying the image data, you can use the toDataURL method to convert the Canvas data into a normal image file format. Function convertCanvasToImage (canvas) {var image = new Image (); image. src = canvas. toDataURL (image/png); return image;} // The save method is used to save the context, and the restore method is used to restore the last saved context. Ctx. save (); ctx. shadowOffsetX = 10; ctx. shadowOffsetY = 10; ctx. shadowBlur = 5; ctx. shadowColor = rgba (0,0, 0, 0.5); ctx. fillStyle = # CC0000; ctx. fillRect (150,100,); ctx. restore (); ctx. fillStyle = #000000; ctx. fillRect (150,100,); // first use the save method to save the current settings, and then draw a shaded rectangle. Then, use the restore method to restore the settings before saving, and draw a rectangle Without shadow // using JavaScript, the canvas Element can easily produce the animation effect var posX = 20, posY = 100; setInterval (function () {context. fillStyle = black; context. fillRect (0, 0, canvas. width, canvas. height); posX + = 1; posY + = 0.25; context. beginPath (); context. fillStyle = white; context. arc (posX, posY, 10, 0, Math. PI * 2, true); context. closePath (); context. fill () ;}, 30); // generates a small dot that moves to the bottom right every 30 milliseconds. At the beginning of the setInterval function, the canvas must be re-rendered with a black background. // It is used to erase the dot from the previous step. // Various motion tracks can be generated by setting the center coordinate. // Increase first and then decrease. Var vx = 10, vy =-10, gravity = 1; setInterval (function () {posX + = vx; posY + = vy; vy + = gravity; //...}); // The x coordinate is always increased, indicating that the motion continues to the right. The y coordinate decreases first, and then increases continuously under the action of gravity, indicating that the coordinates increase first and then decrease. // After the ball keeps rebounding, it gradually moves to Static var vx = 10, vy =-10, gravity = 1; setInterval (function () {posX + = vx; posY + = vy; if (posY> canvas. height * 0.75) {vy * =-0.6; vx * = 0.75; posY = canvas. height * 0.75;} vy + = gravity ;//...}); // once the y coordinate of the ball is at the position of 75% below the screen, the moving speed to the X axis changes to the original 75%, and the rebound height of the last 40% to the y axis. // The getImageData method and putImageData method can process each pixel and then manipulate the image content. // Assuming that the filter is a function for processing pixels, the entire Canvas processing process can be represented by the following code. If (canvas. width> 0 & canvas. height> 0) {var imageData = context. getImageData (0, 0, canvas. width, canvas. height); filter (imageData); context. putImageData (imageData, 0, 0);} // The following are several common solutions. // A grayscale image (grayscale) is the arithmetic average value of three pixel values: Red, green, and blue. This actually converts the image into a black and white format. Assume that d [I] is the red value of a pixel in the pixel array, d [I + 1] is the green value, and d [I + 2] is the blue value, d [I + 3] indicates the alpha channel value. The grayscale algorithm adds the red, green, and Blue values, divides them by 3, and then writes the results back to the array. Grayscale = function (pixels) {var d = pixels. data; for (var I = 0; I <d. length; I + = 4) {var r = d [I]; var g = d [I + 1]; var B = d [I + 2]; d [I] = d [I + 1] = d [I + 2] = (r + g + B)/3 ;}return pixels ;}; // sepia uses red, green, and blue pixels to obtain the weighted average values of the three values, so that the image has an old effect. Sepia = function (pixels) {var d = pixels. data; for (var I = 0; I <d. length; I + = 4) {var r = d [I]; var g = d [I + 1]; var B = d [I + 2]; d [I] = (r * 0.393) + (g * 0.769) + (B * 0.189); // red d [I + 1] = (r * 0.349) + (g * 0.686) + (B * 0.168); // green d [I + 2] = (r * 0.272) + (g * 0.534) + (B * 0.131); // blue} return pixels ;}; // The red mask indicates that the image is reddish. The algorithm sets the red channel to the average value of the red, green, and Blue values, while the green channel and blue channel are both set to 0. Red = function (pixels) {var d = pixels. data; for (var I = 0; I <d. length; I + = 4) {var r = d [I]; var g = d [I + 1]; var B = d [I + 2]; d [I] = (r + g + B)/3; // The average value of the red channel d [I + 1] = d [I + 2] = 0; // set the green channel and blue channel to 0} return pixels ;}; // brightness effect (brightness) indicates to make the image brighter or darker. The algorithm adds a positive or negative value to the red channel, green channel, and blue channel. Brightness = function (pixels, delta) {var d = pixels. data; for (var I = 0; I <d. length; I + = 4) {d [I] + = delta; // red d [I + 1] + = delta; // green d [I + 2] + = delta; // blue} return pixels ;}; // the reverse effect (invert) indicates that the image is displayed in a reversed color. The algorithms for red, green, and blue channels all take their opposite values (255-original values ). Invert = function (pixels) {var d = pixels. data; for (var I = 0; I <d. length; I + = 4) {d [I] = 255-d [I]; d [I + 1] = 255-d [I + 1]; d [I + 2] = 255-d [I + 2];} return pixels ;};

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.