HTML5 Canvas API details

Source: Internet
Author: User

HTML5 Canvas API details
HTML5 is a new standard, and it is replacing the tested html4. HTML5 is a W3C "Working Draft"-meaning it is still in the development stage-it contains rich elements and attributes that both support the current HTML 4.01 version specification. It also introduces several new elements and attributes, which are applicable to many fields that use web pages-audio, video, graphics, data storage, content presentation, and so on. This article focuses on image enhancement: canvas.
The new HTML5 canvas is a native HTML drawing book for JavaScript code and does not use third-party tools. The full HTML5 support across all web browsers is not yet complete, but in the emerging support, canvas can already run well on almost all modern browsers, But Windows®Internet Explorer®Except. Fortunately, a solution has appeared to include Internet Explorer.
Essentially, the canvas element is a whiteboard until you "Draw" some visible content on it. Unlike artists with various paint brushes, you can paint on a canvas in different ways. You can even create and operate animations on the canvas, which is not implemented by using paint brushes and oil colors.

Canvas API (Canvas) is used to generate images in real time on a webpage and manipulate the image content. It is basically a bitmap that can be operated by JavaScript ).
Before use, you must create a canvas webpage element.

 
  
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, and the radius is the radius, startAngle and endAngle are the starting angle and ending angle of the slice (expressed in radians) //, anticlockwise indicates whether to draw a clockwise image (true) or false) // 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 (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.