HTML5 Canvas Eight core technology and its API usage

Source: Internet
Author: User

What is canvas?

The canvas element is part of the HTML5, allowing the scripting language to render bit images dynamically. The canvas is defined by a property in the HTML code of a drawing area to define the height and width ( Note: You cannot set the width and height of the pixel unit "PX" with its properties width and heights). JavaScript code can access the area, generating dynamic graphics with a complete set of drawing functions similar to other generic two-dimensional APIs.

Canvas Eight Core Technologies (3D3R company founder and CEO Ohad Eder-pressman's unique insights):

1. Games

HTML5 is more stereoscopic and sophisticated in web-based image display than Flash, Ohad (3D3R founder and CEO Ohad Eder-pressman) believes that the use of canvas-made images will enable HTML5 games to play a greater potential in fluency and cross-platform. Therefore, the game plays an important role in the HTML5 field.

2. Chart Making

Chart making is often overlooked, but there is no need for charts to communicate and collaborate within or between enterprises. Some developers now use HTML/CSS to complete the icon creation, but ohad that you can do it entirely with canvas. In addition, it is good to use SVG (Scalable Vector graphics) to complete the chart creation.

3.banner Advertising

Flash has been a glorious era, the smartphone has not yet appeared. Now and in the future of the smart phone era, HTML5 technology can play a huge role in banner advertising, the use of canvas to achieve dynamic advertising effect is more appropriate.

4. Simulator

Ohad that the simulator product can be fully implemented in JavaScript, both visually and in terms of its core functionality.

5. remote computer control

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

6. Font Design

Custom rendering for fonts will be completely web-based and can be implemented using HTML5 technology.

7. Graphic Editor

Ohad predicts that the graphical editor will be able to 100% Web-based implementations.

8. Other content that can be embedded in the site

Like charts, audio, and video, there are many elements that better integrate with the web and do not require any plugins.

Canvas API Usage:

Before using, you need to create a new canvas page element.

<canvas height= "id=" MyCanvas "width=" >    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) {    var ctx = Canvas.getcontext (' 2d ');} The GetContext method specifies a parameter of 2d, which indicates that the canvas object is used to generate a 2D pattern (that is, a planar pattern). If the parameter is 3d, it is used to generate a 3D image (that is, a stereoscopic pattern), which is actually called the WebGL API alone (see other blogger articles).

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 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 Alignment ctx.textalign = left;//Set the fill color ctx.fillstyle = #008600; Set the font content, as well as the position on the canvas ctx.filltext (hello!, 10, 50); Draw 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 the starting and ending angles of the sector (in radians)//, Anticlockwise indicates that the diagram should be drawn counterclockwise (true) or clockwise (false)

Draw a solid circular 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 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);} The IMAGE.SRC = Image.png;//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 this arrayThe degree equals 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 re-convert the canvas data into a generic 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 to take red, green, the arithmetic mean value of the blue three pixel values, 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 value, making 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;}; A 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]; Varb = D[i + 2];        D[i] = (r+g+b)/3; Red channel averaging d[i + 1] = D[i + 2] = 0; Both the green channel and the blue Channel are set to 0} return pixels; The Luma effect (brightness) refers to making the image brighter or darker. The algorithm adds a red channel, a green channel, and a blue channel, plus a positive or 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;}; A reversal effect (invert) is a picture that renders an inverted color effect. 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;};

HTML5 Canvas Eight core technology and its API usage

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.