"HTML" Canvas (4)-Advanced

Source: Internet
Author: User

Canvas Advanced Features

Zoom in and zoom out : Use The scale function to zoom in and out of the graph

Prototype: Scale (x, y); X means scaling on the x-axis, which is horizontal, and y means scaling on the y-axis, which is the vertical direction.

Enlarge:


var C=document.getelementbyid (' MyCanvas '); var ctx=c.getcontext (' 2d ');//start drawing a length of 150 for the starting point of the coordinates (10,10), A black rectangle of width 100 ctx.beginpath (); ctx.strokestyle= ' #000 '; Ctx.strokerect (10,10,150,100);//enlarge its value 3 times times along the x-axis and y-axis direction, Use the same code to redraw a gray rectangle Ctx.scale (3,3); Ctx.beginpath (); ctx.strokestyle= ' #ccc '; Ctx.strokerect (10,10,150,100);

From the running effect, although the same code is used, the second drawn gray rectangle is magnified 3 times times, and the starting coordinates are magnified 3 times times.

Zoom Out:


var C=document.getelementbyid (' MyCanvas '); var ctx=c.getcontext (' 2d ');//start drawing a length of 150 for the starting point of the coordinates (50,50), Black Rectangular ctx.beginpath width 100 (); ctx.strokestyle= ' #000 '; Ctx.strokerect (50,50,150,100);// Reduce its value by 0.5 times times along the x-axis and y-axis, and redraw a gray rectangle Ctx.scale (0.5,0.5) with the same Code Ctx.beginpath (); ctx.strokestyle= ' #ccc '; ctx.strokerect (50,50,150,100);
From the running effect, although the same code is used, the second drawn gray rectangle is reduced by 0.5 times times, and the starting coordinates are 0.5 times times smaller.

When using the scale function, if the argument is negative, you can flip the graph :


var C=document.getelementbyid (' MyCanvas '), Var ctx=c.getcontext (' 2d '), var image=new image (), image.src= '. /images/travel.jpg '; Image.onload=function () {ctx.drawimage (image,0,0); Ctx.scale (1,-1);//Set negative numbers to flip the picture ctx.drawimage (image,192,-168);};

panning: Translate () function

prototype: Translate (x, y); X represents panning on the x-axis, which translates horizontally, and y means panning on the y-axis, which translates vertically

var C=document.getelementbyid (' MyCanvas '); var ctx=c.getcontext (' 2d '); Ctx.beginpath (); ctx.strokestyle= ' #000 '; Ctx.strokerect (10,10,150,100); ctx.translate (50,100);//indicates moving right 50 in the horizontal direction, moving vertically 100ctx.beginpath (); ctx.strokestyle= ' # CCC '; Ctx.strokerect (10,10,150,100);

Rotation:rotate (angle); Angle are radians, not angles. If the angle is angle, then the conversion to radians is angle*math.pi/180

var C=document.getelementbyid (' MyCanvas '); var ctx=c.getcontext (' 2d '); Ctx.beginpath (); ctx.strokestyle= ' #000 '; Ctx.strokerect (200,50,100,50); ctx.rotate (45*math.pi/180); ctx.strokestyle= ' #f00 '; Ctx.strokerect (200,50,100,50);

As shown, rotate () rotates in the center of the canvas's starting coordinates (0,0), and if you want the graphic to rotate in its own center, you need to use the translate () function:

var C=document.getelementbyid (' MyCanvas '); var ctx=c.getcontext (' 2d '); Ctx.beginpath (); ctx.strokestyle= ' #000 '; Ctx.strokerect (200,50,100,50); ctx.translate (250,75); ctx.rotate (45*math.pi/180); ctx.translate ( -250,-75); Ctx.beginpath () ctx.strokestyle= ' #f00 '; Ctx.strokerect (200,50,100,50);

Move the start coordinate of the canvas to the right by 250, move down 75, move to the center of the rectangle you are drawing, then start rotating 45 degrees, then move the start coordinate of the canvas to the left 250, move up 75 degrees, then move back to the original position, so that the graph is rotated in its own center.


Graphics Rendering:canvas provides many APIsto manipulate colors toachieve gradients, inverse colors, and more.

Drawing A color gradient effect: gradients of colors are divided into linear and radial gradients

Linear gradients are implemented using the Createlineargradient function and the Addcolorstop function

createlineargradient (x1,y1,x2,y2); The 4 parameters are the starting point coordinates (X1,Y1) and the end point coordinates (X2,Y2) of the gradient respectively;

addcolorstop (Position,color); The position parameter must be a numeric value between 0.0 and 1.0, representing the relative position of the color location in the gradient, which represents the color of the gradient.

var C=document.getelementbyid (' MyCanvas '), Var ctx=c.getcontext (' 2d '), Var grd=ctx.createlineargradient (0,0,200,0); Grd.addcolorstop (0.2, ' #0f0 '); Grd.addcolorstop (0.8, ' #f00 '); Ctx.fillstyle=grd;ctx.fillrect (0,0,200,100);

Radial gradients: Using the Createradialgradient function and the Addcolorstop function

createradialgradient (X0,Y0,R0,X1,Y1,R1); The parameter x0, y0 is the center coordinate of the starting circle, the r0 is the diameter of the start circle, the center coordinate of the X1, y1 bit end circle, and the diameter of the end circle.

var C=document.getelementbyid (' MyCanvas '), Var ctx=c.getcontext (' 2d '), Var grd=ctx.createradialgradient ( 100,100,10,100,100,50); grd.addcolorstop (0, ' #0f0 '); Grd.addcolorstop (1, ' #f00 '); Ctx.fillstyle=grd;ctx.fillrect ( 0,0,200,200);

Color synthesis

The Globalcompositeoperation property describes how colors drawn to the canvas are combined with existing colors on the canvas. here is a list of the values that you might want to set and what they mean, where the word source refers to the color that will be drawn to the canvas, destination refers to a color that already exists on the canvas, and the default value is Source-over

Copy: Draw only new graphics, delete all other content

Darker: Where the shape overlaps, the color is determined by subtracting two color values.

Destination-atop: The content that is already on the canvas is retained only where it overlaps with the new graphic. After the new graphic is drawn with the content.

Destination-in: There are existing graphics overlays on the new drawing and canvas, and the contents of the canvas are preserved. All other content is transparent.

Destination-out: Existing content is retained on the canvas where there is no overlap between the content and the new shape. The rest of the content is transparent.

Destination-over: The new drawing is drawn on the canvas after the content is already there.

Lighter: Where the graphic overlaps, its color is determined by the addition of two color values.

Source-atop: New graphics are drawn only where there is overlapping content on the new drawing and canvas.

Source-in: New graphics are drawn and all other content is transparent in the new drawing and where content overlaps on the canvas.

Source-out: New graphics are only drawn where there are no overlapping shapes on the canvas.

Source-over: The new drawing is drawn with the top of the drawing already on the canvas. The default value.

XOR: In other places where overlap and normal drawing are made, the graphic becomes transparent.

var C=document.getelementbyid (' MyCanvas '); var ctx=c.getcontext (' 2d '); ctx.fillstyle= ' #0f0 '; Ctx.fillrect ( 10,10,50,50); ctx.globalcompositeoperation= ' XOR '; Ctx.beginpath (); ctx.fillstyle= ' #f00 '; Ctx.arc (50,50,30,0,2* Math.PI); Ctx.fill ();

Color inversion (inverting): The color of each pixel of the graph is reversed.

var C=document.getelementbyid (' MyCanvas '), Var ctx=c.getcontext (' 2d '), var image=new image (), image.src= '. /images/travel.jpg '; Image.onload=function () {ctx.drawimage (image,0,0); var imagedata=ctx.getimagedata (0,0,250,250 var pixels=imagedata.data;//iterates through each pixel and takes the inverse for (Var i=0,n=pixels.length;i<n;i+=4) {Pixels[i]=255-pixels[i] to the RGB value; PIXELS[I+1]=255-PIXELS[I+1];p ixels[i+2]=255-pixels[i+2];} Pixel Redraw Ctx.putimagedata (imagedata,250,0) at the specified position;};
Grayscale Control: The practice is similar to the inverse, first of all, the graph of each pixel gray-scale calculation

var C=document.getelementbyid (' MyCanvas '), Var ctx=c.getcontext (' 2d '), var image=new image (), image.src= '. /images/travel.jpg '; Image.onload=function () {ctx.drawimage (image,0,0); var imagedata=ctx.getimagedata (0,0,250,250 var pixels=imagedata.data;//iterates through each pixel and takes the RGB value back for (Var i=0,n=pixels.length;i<n;i+=4) {var grayscale=pixels[i]* 0.3+pixels[i+1]*0.59+pixels[i+2]*0.11;pixels[i]=grayscale;//redpixels[i+1]=grayscale;//greenpixels[i+2]= grayscale;//blue}//pixel Redraw Ctx.putimagedata (imagedata,250,0) at the specified position;
Shadow Effect:thecanvas API contains properties that automatically add drop-down shadows to graphics. the color of the shadow can be specified using the Shadowcolor property, and may be changed by Shadowoffsetx and Shadowoffsety properties. In addition, the amount of feathering applied to the edge of the shadow can also be set using the Shadowblur property.


var C=document.getelementbyid (' MyCanvas '); var ctx=c.getcontext (' 2d '); ctx.shadowcolor= ' #f00 '; ctx.shadowblur=10;// Feather ctx.shadowoffsetx=20;ctx.shadowoffsety=30;var image=new image (); Image.src= '.. /images/travel.jpg '; Image.onload=function () {ctx.drawimage (image,0,0);};

Custom Artboards

The main ideas and steps are as follows:

(1) When the mouse is pressed, start painting, here need to join the mouse press event.

(2) When the mouse bounces, the end of the painting, here to add the mouse bounce event.

(3) When the mouse is pressed and moved, in the path of the mouse to draw lines, here need to join the mouse movement event.

The export function of canvas canvas:

Add a picture export function to the artboard, which copies the image on the canvas artboard so that it appears as a picture format. use Canvas.todataurl (' image/png ');

If you want to save the picture as a picture file, you also need to use tools such as PHP or ASP.

Now let's create a new tag on the page and then use the representation of the copied canvas content.



The HTML section is as follows:

<canvas id= "MyCanvas" width= "" "height=" >    your browser does not support HTML5    </canvas>    <br/>    <button onclick= ' linecolor= "yellow"; >Yellow</button>    <button onclick= ' linecolor= "red"; >Red</button>    <button onclick= ' linecolor= "Blue"; >Blue</button>    <button onclick= ' linecolor= "green"; >Green</button>    <button onclick= ' linecolor= "white"; >White</button>    <button onclick= ' linecolor= "Orange"; >orange</button>    <br/>    <br/>    <button onclick= "linew=4" >4px</button >    <button onclick= "linew=8" >8px</button>    <button onclick= "linew=16" >16px</ button>    <button onclick= "copyimage (); >Export</button>    <br/>    

JavaScript section:

var C=document.getelementbyid (' MyCanvas '); var ctx=c.getcontext (' 2d ');//Draw a black rectangle ctx.fillstyle= ' black '; ctx.fillrect (0,0,600,300);//press the tag var onoff=false;var oldx=-10;var oldy=-10;//Set the color var linecolor= ' white ';//Set the line width var linew=4;// Add Mouse Move Event C.addeventlistener (' MouseMove ', draw,true);//Add Mouse press event C.addeventlistener (' MouseDown ', down,false);// Add Mouse Bounce Event C.addeventlistener (' MouseUp ', up,false); function down (event) {onoff=true;oldx=event.pagex-10;oldy= event.pagey-10;} function up () {onoff=false;} function Draw (event) {if (onoff==true) {var newx=event.pagex-10;var newy=event.pagey-10;ctx.beginpath (); Ctx.moveto ( Oldx,oldy); Ctx.lineto (newx,newy); ctx.strokestyle=linecolor;ctx.linewidth=linew;ctx.linecap= ' Round '; Ctx.stroke ( ); oldx=newx;oldy=newy;}} Export picture function Copyimage (event) {var img_png_src=c.todataurl (' image/png ');d Ocument.getelementbyid (' image_png '). SRC=IMG_PNG_SRC;}

Author: Zhi Zhi

Sign: The road long its repair far XI, I will go up and down and quest.


"HTML" Canvas (4)-Advanced

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.