HTML5 is an emerging standard that is replacing the tried and tested HTML4 faster and faster. HTML5 is a "work draft"-meaning it is still in the development phase-it contains rich elements and attributes that support the current HTML 4.01 version specification. It also introduces several new elements and attributes that apply to many areas where Web pages are used-audio, video, graphics, data storage, content rendering, and so on. This article focuses on graphics enhancements: canvas.
The new HTML5 canvas is a native HTML drawing book for JavaScript code and does not use third-party tools. Full HTML5 support across all Web browsers is not yet complete, but in emerging support, canvas can already run well on almost all modern browsers, but Windows? Internet Explorer? Except. Fortunately, a solution is already in place, including Internet Explorer.
Essentially, a canvas element is a whiteboard until you "paint" some visual content on it. Unlike artists with a variety of brushes, you use different methods to paint on canvas. You can even create and manipulate animations on the canvas, which is not possible with brushes and paints.
The canvas API is used to generate images in real time on a Web page and manipulate the image content, which is basically a bitmap (bitmap) that can be manipulated with JavaScript.
Before using, you need to create a new canvas page element.
<canvas id= "MyCanvas" width= "height=" > your browser does not support canvas! </canvas><!--If the browser does not support this API, the text in the middle of the canvas label will be displayed-"Your browser does not support canvas! ”。 -
Each canvas element has a corresponding context object (the context object), and the canvas API is defined above the context object, so you need to get this object by using the GetContext method.
var canvas = document.getElementById (' MyCanvas '); if (Canvas.getcontext) {
The canvas canvas provides a flat space for drawing, where each point has its own coordinates, x is the horizontal axis, and y represents the vertical coordinate. The origin (0, 0) is in the upper-left corner of the image, the positive direction of the x-axis is the origin, and the positive direction of the y-axis is the origin.
Draw Path
The Beginpath method represents the start drawing path, the MoveTo (x, Y) method sets the starting point of the segment, the LineTo (x, Y) method sets the end point of the segment, and the stroke method is used to color the transparent segment.
Ctx.beginpath (); Start path Draw Ctx.moveto (20, 20); Set the starting point of the path with coordinates of (20,20) Ctx.lineto (200, 20); Draw a line to (200,20) Ctx.linewidth = 1.0; Set the line width Ctx.strokestyle = "#CC0000"; Sets the color of the line Ctx.stroke (); Line coloring, then the entire line becomes visible//moveto and LineTo methods can be used multiple times. Finally, you can use the Closepath method to automatically draw a line from the current point to the starting point to form a closed graph, eliminating the use of a LineTo method.
Draw a rectangle
The FillRect (x, y, Width, height) method is used to draw a rectangle whose four parameters are the x-coordinate, the y-coordinate, and the width and height of the vertex of the upper-left corner of the rectangle, respectively. The FillStyle property is used to set the fill color of the rectangle.
Ctx.fillstyle = ' yellow '; Ctx.fillrect (();//strokerect method is similar to FillRect, which is used to draw a hollow rectangle. Ctx.strokerect (10,10,200,100); The//clearrect method is used to clear the contents of a rectangular area. Ctx.clearrect (100,50,50,50);
Draw Text
Filltext (string, x, y) is used to draw text whose three parameters are the text content, the x-coordinate of the starting point, and the y-coordinate. Before using, use font to set font, size, style (similar to the Font property of CSS). Similar to this is the Stroketext method, which is used to add hollow words.
Set Font Ctx.font = "Bold 20px Arial"; Set the Alignment ctx.textalign = "Left";//Set fill Color Ctx.fillstyle = "#008600"; Set the font content, as well as the position on the canvas ctx.filltext ("hello!", 10, 50); Draw the Hollow character Ctx.stroketext ("hello!", "Ten,"); the//filltext method does not support text break, that is, all text appears in one line. So, if you want to generate multiple lines of text, you only have to call multiple Filltext methods.
draw circles and slices
The Arc method is used to draw a fan
Ctx.arc (x, y, radius, startangle, Endangle, anticlockwise); The x and Y parameters of the//arc method are the center coordinates, RADIUS is the radius, StartAngle and endangle are fan-shaped starting angles and end angles (in radians)//,anticlockwise indicate whether you should draw counterclockwise (true) or clockwise (false)//draw a solid round ctx.beginpath () ; Ctx.arc (0, math.pi*2, true); Ctx.fillstyle = "#000000"; Ctx.fill ();//Draw Hollow round ctx.beginpath (); Ctx.arc (0, math.pi*2, true); Ctx.linewidth = 1.0; Ctx.strokestyle = "#000"; Ctx.stroke ();
Set Gradient Color
The Createlineargradient method is used to set the gradient color.
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 starting coordinates, and X2 and Y2 are the end coordinates. With different coordinate values, you can generate top-down, left-to-right gradients, and so on ctx.fillstyle = Mygradient;ctx.fillrect (10,10,200,100);
Set Shadow
A series of shadow-related methods that you can use to set the shadow.
Ctx.shadowoffsetx = 10; Set the horizontal displacement ctx.shadowoffsety = 10; Set Vertical Displacement Ctx.shadowblur = 5; Set the fuzziness Ctx.shadowcolor = "Rgba (0,0,0,0.5)"; Set Shadow Color Ctx.fillstyle = "#CC0000"; Ctx.fillrect (10,10,200,100);
Canvas allows you to insert an image file into the canvas by using the DrawImage method to redraw the canvas after reading the picture. var img = new Image (); img.src = "Image.png"; Ctx.drawimage (img, 0, 0); Sets the corresponding image object and its position on the canvas//Because the image loading takes time, the DrawImage method can only be called after the image is fully loaded, so 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 of the image file (that is, the IMG tag), the second and third parameters are the coordinates of the upper-left corner of the image in the//canvas element, in the above example (0, 0) means 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 contents of a canvas, returning an object that contains information for each pixel. var imageData = context.getimagedata (0, 0, canvas.width, canvas.height); The//imagedata object has a data property whose value is a one-dimensional array. The value of the array, in turn, is the red, green, blue, and alpha channel values for each pixel, because//the length of the array is equal to the pixel width of the image × the pixel height of the image x 4, and the range of each value is 0–255. This array is not only readable, but also writable,//So by manipulating the value of this array, you can achieve the purpose of manipulating the image. After modifying this array, the contents of the array are redrawn//made on the canvas using the Putimagedata method. Context.putimagedata (imageData, 0, 0);//After making changes to the image data, you can use the TodataUrl method to convert the canvas data back 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 revert to the context of the last saved environment. Ctx.save (); Ctx.shadowoffsetx = 10;ctx.shadowoffsety = 10;ctx.shadowblur = 5;ctx.shadowcolor = "Rgba (0,0,0,0.5)"; ctx.fillStyle = "# CC0000 "; Ctx.fillrect (10,10,150,100); Ctx.restore (); Ctx.fillstyle = "#000000"; Ctx.fillrect (180,10,150,100);//First Save the current setting with the Save method, and then draw a shaded rectangle. Then, using the Restore method, restore the pre-save settings, Draw//a rectangle without shading//using JavaScript, can easily animate on the canvas element var PosX =, 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, 0, math.pi*2, true); Context.closepath (); Context.fill ();}, 30);//The effect of producing a small dot that moves down to the right at every 30 milliseconds. At the beginning of the SetInterval function, the canvas was re-rendered with a black background,//in order to erase the small dots from the previous step. By setting the center coordinate, various motion trajectories can be produced. Rise first and then descend. var VX = ten, VY= -10, gravity = 1;setinterval (function () {PosX + = VX; PosY + = VY; VY + = gravity; // ...});/ The/X coordinate always increases, indicating a continuous right motion. The y-coordinate becomes smaller and then increases with gravity, indicating that it rises first and then decreases. The ball is constantly bouncing back, gradually tending to static var VX = ten, 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 75% of the bottom of the screen, the speed of movement to the x-axis changes to 75%, while the y-axis bounces 40% of the previous bounce height. With the Getimagedata method and the Putimagedata method, each pixel can be processed to manipulate the image content. Assuming that filter is a function that handles pixels, the entire process for the canvas can be represented in the following code. if (canvas.width > 0 && canvas.height > 0) {var imageData = context.getimagedata (0, 0, Canvas.width, can Vas.height); Filter (ImageData); Context.putimagedata (imageData, 0, 0);} Here are a few common ways to handle this. Grayscale (grayscale) is the arithmetic mean of the three pixel values of red, green, and blue, which actually turns the image into black and white. Suppose D[i] is the red value of one pixel in the array of pixels, then d[i+1] is the green value, D[i+2] is the blue value, D[i+3] is the alpha channel value. The algorithm that turns into grayscale is to add the red, green, and blue values and divide by 3, then write the result 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;};/ /Retro effect (sepia) is the red, green, blue three pixels, respectively, the three values of a certain weighted average, so that the image has an archaic 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;};/ /Red mask refers to the effect of making an image appear red. The algorithm is to set the red channel to the average of the red, green, and blue values, and the green channel and the blue Channel are 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; Red channel averaging d[i + 1] = D[i + 2] = 0; Green channel and blue channel are set to 0} return pixels;};/ /Luma effect (brightness) refers to making the image brighter or darker. The algorithm will be red channel, green channel, blue channel, plus a positiveor negative value. 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;};/ /Invert effect (invert) refers to the effect that a picture renders a color reversal. The algorithm takes the opposite value (255-the original value) for the red, green, and blue channels. 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;};If you do not understand, please add QQ Group: 135430763 Study together!
HTML5 Canvas API Detailed