Acquaintance HTML5 Canvas

Source: Internet
Author: User

Canvas is an HTML API that we can use to generate images in real time in a Web page.

Article guide

1. Required Skills

2. Functions for drawing

Example:

-Conversation bubbles--heart--clocks--stars in the planets--

-Palette--mouse drawing--rotating small squares-

3. Image processing

Example:

-Grayscale and rollover effects of images--color picker-

-Magnifying glass--gaussian blur of the image-

I. Required Skills
<canvas id= "Canvas" width= "height=" >     not support Canvas browser, you will see this sentence! </canvas>

The width of the control is to be written in the inline style, as in the above. So we have a canvas element, and then we can manipulate it:

var canvas = document.getElementById (' canvas '); if (canvas.getcontext) {    var content = Canvas.getcontext (' 2d ');}

Gets the element while also acquiring the canvas's 2D drawing environment. If you're using 3D graphics, use WebGL.

Two. Functions for drawing

Then, we're going to start drawing on the canvas. Its canvas is such a grid:

2.1 Rectangle

Only the functions of this shape are supported in the canvas, and the other shapes are combined to achieve them.

// draw a filled rectangle // draw a rectangle with only a border // clears the specified rectangular area

where (x, y) refers to the coordinates of the upper-left corner of the rectangle.

[View source] [run result]

2.2 Path
12. then, do some drawing operations with some drawing methods 3. Then close the path--closepath ()4. We've created the path, and then it's filling or drawing the path to our canvas--stroke ()/fill ()

For example, draw a triangle:

[View source] [run result]

It is important to note that two of these triangles, different colors, may be accidentally problematic, so we may sometimes need the help of the Save () and restore () functions to achieve the effect of local effect. As shown in the example source above:

1               2Content.save ();//effect of local effect3Content.fillstyle = ' Red ';4Content.beginpath ();//Beginpath () may go wrong when not written, so make sure the Beginpath and Closepath are relative5Content.moveto (100,100);6Content.lineto (200,200);7Content.lineto (300,200);8 Content.closepath ();9 Content.fill ();Ten Content.restore (); One  A  - Content.beginpath (); -Content.moveto (100,200); theContent.lineto (200,300); -Content.lineto (300,300); - Content.closepath (); -Content.fill ();
View Code

The canvas also provides two functions for moving brushes:

// move the brush to the specified (x, y) position // draws a line at the position of the current brush to the specified (x, y) position

Try the MoveTo () method and we can draw a smiley face:

[View source] [run result]

Using the MoveTo and LineTo methods together, we can achieve the effect of a mouse drawing on an artboard like a brush:

[View source] [run result]

Then we strictly according to the above-mentioned standard steps, 1,2,3,4 and combined with the circle of the function, you can draw a clock, a little improvement is a ticking clock:

[View source] [run result]

2.3 Writings

Filltext (' Text to display ', x-coordinate, y-coordinate) This method does not support text break, and multiple lines of text can only be called multiple times

With the Filltext () method we can write text on canvas:

[View source] [run result]

2.4 Round and scalloped
Ctx.arc (x, y, radius, startangle, Endangle, anticlockwise);(x, y) --Center coordinate radius--radius startangle--The starting angle of the sector (radians) endangle--the end angle (radians) of the fan, anticlockwise--when the diagram is drawn clockwise (true) or counterclockwise ( false) painting

[View source] [run result]

In conjunction with the RGB color-related operations, we can make a palette-like effect:

[View source] [run result]

2.5 Irregular Graphics

We can draw a curve to get irregular graphics, and canvas provides us with two tall functions:

-------------------------------
#quadraticCurveTo (cp1x, cp1y, X, y) (cp1x,cp1y)--control points This function represents a two-time curve drawn from the current brush position to (x, y)-------------------------------# Beziercurveto (cp1x, cp1y, CP2X, cp2y, X, y) (cp1x,cp1y)--Control point 1 (CP2X,CP2Y)--Control point 2 This function represents drawing a Bezier curve from the current brush position to (x, y)
-------------------------------

I don't know exactly what these two curves mean, but that's probably what it looks like:

Try the Quadraticcurveto function:

[View source] [run result]

Try the Beziercurveto function:

[View source] [run result]

2.6 Gradients and Shadows

# gradient: var mygradient = ctx.createlineargradient (x1, y1, x2, y2); (x1,y1)--Start coordinate  (x2,y2)--End coordinate Mygradient.addcolorstop (0, "#BABABA");--Add Start color mygradient.addcolorstop ( 1, "#636363"//  Set Horizontal shift/ /  set Vertical shift //  set blur degree // Set Shadow color

A less-than-good example, in any case, also used a gradient:

[View source] [run result]

It uses the clip () method to implement the star, which is clip-path with a CSS attribute, which I tried before:

Please poke [source code] [Example]

2.7 Transformations

There are several transformation functions that we are familiar with in the canvas:

translate (x, y)--Pan rotate (angle)--Rotation scale (x, y)--Zoom transform (A, B, C, D, E, f)--transform the above transformation function is based on the transformation matrix:   a   c< c5/>e[b   D   F]   0   0   1

Simple Small Example:

[View source] [run result]

Three. Image processing
var myimagedata = ctx.createimagedata (width, height); Ctx.getimagedata (left, top, width, height); // reads the contents of the canvas, returns an object and has a data property that allows us to manipulate the pixels of the page. ctx.putimagedata (myimagedata, DX, dy); // Redraw the manipulated object in the canvas // The DrawImage method that we use, sets the corresponding image object, and its position on the canvas

Using the Getimagedata () method to get to an Image object, access its Data property to get a group of pixels, we handle the pixel so that we can process the image with canvas.

3.1 Grayscale Effect

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, and 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.

1                for (var i=0;i<data.length;i+=4) {2                     var avg = (data[i]+data[i+1]+data[i+2])/3; 3                     // R 4                     // g 5                     // b 6                 }
View Code

3.2 Retro Effect

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.

1   for(vari = 0; i < d.length; i + = 4) {2       varR =D[i];3       varg = d[i + 1];4       varb = D[i + 2];5D[i] = (R * 0.393) + (G * 0.769) + (b * 0.189);//Red6D[i + 1] = (R * 0.349) + (G * 0.686) + (b * 0.168);//Green7D[i + 2] = (R * 0.272) + (G * 0.534) + (b * 0.131);//Blue8}
View Code

3.3 Reversal Effect

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.

1  for (var i = 0; i < d.length; i + = 4) {2         d[i] = 255- d[i]; 3         D[i+1] = 255-d[i + 1]; 4         D[I+2] = 255-d[i + 2]; 5     }
View Code

I tried the effect of the grayscale and reversed the graph:

[View Source]

Note that there may be a problem with the Getimagedata () method when we write our own local demo to run the view results, for example, to report this error: Failed to execute ' getimagedata ' on ' CANVASRENDERINGCONTEXT2D ': The canvas has been tainted by Cross-origin data

We know that this is a domain and local operation and other related issues, when we ourselves enable the server locally, localhost access is available.

3.4 Color Picker

Realize the idea: through Getimagedata (x,y,1,1) to get the current mouse position of a pixel image object, through its Data property operation to get its pixel value, that is, we want the RGB value.

[View Source]

3.5 Magnifier

In fact, the DrawImage method can have multiple parameters, providing richer functionality:

1 ctx.drawimage (image, DX, dy); 2 ctx.drawimage (image, DX, dy, dwidth, dheight); 3  Ctx.drawimage (image, SX, SY, swidth, sheight, dx, dy, dwidth, dheight);

Each parameter is like this:

Then we can use the DrawImage method in the original image transformation to the drawing of the image to do a comparable amplification operation, you can achieve the effect of the magnifying glass.

"View Source"

3.6 Gaussian blur of images

In fact, CSS has a not so good compatibility Filter property, you can easily achieve the effect of blurred image:

/**    /-moz-Filter:blur (20px     ); -ms-Filter:blur (20px);             Filter:blur (20px);

"View Source"

But using canvas can achieve a true Gaussian blur (the Balabala of the algorithm).

Here's a well-implemented Gaussian blur of js:"stackblur"

Using it, we can easily realize the Gaussian blur of the image: "View Source"

The source of the article in the demo are placed on GitHub, open may be some slow, if the first time can not open, refresh a bit will be good.

Four. Resources

All the properties and methods of the drawing environment in canvas can be found here: "canvasrenderingcontext2d interface"

"Use CSS to convert a picture into a blur (frosted glass) effect"

"canvas api"

"javascript Standard Reference Tutorial canvas"

Acquaintance HTML5 Canvas

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.