javascript: Drawing 2D graphics with canvas

Source: Internet
Author: User
Tags linecap

One of HTML5 's most welcome new features is the canvas element, which is responsible for setting an area in the page and then using JavaScript to make a dynamic drawing.

    • Basic usage

   

<id= "Drawing"  widht= "Max"  height= " > a drawing of Somethind </ Canvas >

After setting the canvas, go to the drawing context, via get. Context ("2d") method

var  drawing = document.getElementById ("drawing"), if (Drawing.getcontext) {var context = Drawing.getcontext ("2d");}

Using Todataurl (), the parameter is the MIME-type format of the image, such as Todataurl ("Image/png")

var  drawing = document.getElementById ("drawing"), if (Drawing.getcontext) {var context = Drawing.getcontext ("2d"); var Imguri = Context.todataurl ("image/png"); var image = Document.createelement ("img"); image.src = img; Documemt.body.appendChild (image);}
    • The context

The coordinates of the X-y context begin with the upper-left corner of the canvas element. Use the 2D context to draw rectangles, arcs, and paths. The two basic operations of the three-way context are fill and stroke, attribute FillStyle () implements the fill effect, and attribute Strokestyle () implements the stroke effect, which parameters are the string representing the color, the gradient object, and the Pattern object.

1) Draw Rectangle

There are three ways to draw a rectangle: FillRect (), Strokerect (), Clearrect (). All three methods accept four parameters, x coordinate, y coordinate, width,height.

The fill color of FillRect () is specified by the Fillestyle () method, and the same stokerect () is specified by Strokestyle ().

The width of the stroke line is specified by LineWidth (), linecap Specifies whether the end of the line is flat (butt), round (round) or square (square), and LineJoin () controls how the lines intersect (round intersection round, oblique bevel, miter miter )

Clearrect () is used to clean up the specified area on the canvas.

    

Context.fillrect (10,10,50,50), Context.fillstyle ("Red"), Context.stokerect (20,20,50,50); Context.strokestyle (" Green "), Context.linewidth (5), Context.linecap (' round '), Context.linejoin (" Round ");

2) Draw the path

The draw Path first calls Beginpath (), which indicates that a new path is to be drawn. Then call the following method to draw the actual path.

1) Draw arc arc (x,y,radius,staryangle,endangle,counterclockwise)---with (x, y) as the center, RADIUS is radius, start angle is startangle, end angle is Endangle A counterclockwise value of false indicates a clockwise calculation.

2) Draw the Arc ArcTo (X1,y1,x2,y2,radius) from the previous point, with X2,y2 as the end point, through X1,y1

3) Draw the Curve Beziercurveto (c1x,c1y,c2x,c2y,x,y) from the previous point, draw the curve from the top, the end point to X, Y, and (c1x,c1y) (C2X,C2Y) as the control point

4) draw a straight line from the previous point lineTo (x, y)

5) MoveTo (x, Y) Drawing chart move to X, y point

6) Quadraticcurveto (cx,cy,x,y) plots two curves with x,y,cx,cy as Control point

7) Rect (X,y,widht,height) to draw a rectangular path

After the path is created, call Closepath () to draw the path connecting to the starting point, call Fill () to fill the path, and call stroke () to create a stroke path.

The following code draws the clock:

    

Outer Circle Context.arc (100,100,99,0,2*math.pi,false);//Inner Circle Context.arc (100,100,94,0,2*math.pi,false); Context.moveTo ( 100,100); Context.lineto (100,15); Context.moveto (100,100); Context.lineto (100,30);//Stroke Path Context.storke ();

3) Draw Text

The text is drawn mainly by two methods: Filltext (), Stoketext (), receiving four parameters: text string, x-coordinate, y-coordinate, optional maximum width.

The two methods are based on the following attributes: Font, textAlign, textbaseline

The value of the textalign has a start end center, which controls the horizontal alignment, the Textbaseline value is Middle,top,bottom, and the vertical alignment is controlled.

The width of the auxiliary measurement text is meaturetext (text string), and the returned object has only one width property, which measures the width of the text with the Font,textalign,textbaseline property set.

var fontsize = 140px;context.font = FontSize + "  italic  Arial"; Context.textalig = Center;context.textbaseline = " Top ";" while (Context.meaturetext ("Hello"). Width > $) {fontsize--; Context.font = FontSize + "  Italic  Arial" ;} Context.fillstyle ("Red"); Context.filltext ("Hello", 10,10);

4) Transform

Ways to modify the change matrix:

Rotate (angle): Rotates the angle angle around the origin.

Scale (Scalex,scaley): Scales the image, multiplies the X-direction by ScaleX, multiplies the Y-direction by ScaleY

Translate (x, y): Move the coordinate origin to the (x, y) point

Transform (M1_1,m2_1,m2_1,m2_2,dx,dy): Modifying the transformation matrix directly

Settransforn (M1_1,m2_1,m2_1,m2_2,dx,dy): Resets the transformation matrix to the default state, calling the Transform method

The settings can be saved by Context.save () and then Context.restore () to the previous setting from the current set level.

5) Drawing the image

Using the method DrawImage () to draw the image, different implementation effects This method needs to pass in different parameters.

The simplest parameter is the image element of the HTML, the start of the plot area, the x-coordinate, the y-coordinate

    

var img = document.images[0];context.drawimage (img,10,10);

Draw part of the image into the canvas:

The parameters are: Image element, source image coordinates start x value, y value, Width,height, x value of target image, Y value, width,height.

Draw a canvas element to another canvas

6) Shadow

Shadowcolor = color value

Shadowoffsetx = offset in x direction

Shadowoffsety = offset in y direction

Shadowblur = fuzzy value

7) Gradient

    • Linear gradient

Call Createlineargradient (start x coordinate, start y-coordinate, end-point x-coordinate, end-point y-coordinate), return canvasgradient gradient object. After creating the gradient object, call Addcolorstop (position of the color tag, CSS color value), the position of the color tag from 0 to 1, 0 for the starting color, 1 for the end color, the gradient object returned by this method to FillStyle or Storkestyle (), You can use gradients to draw shapes or strokes.

      

var gradient = context.createlineargradient (30,30,70,70); Gradient.addcolorstop (0, "white"); Gradient.addcolorstop ( 1, "blue") Context.fillstyle = Gradient;context.fillrect (30,30,40,40);
    • Radial gradient

The method is similar to the linear gradient, context.createradialgradient (x coordinate of the start circle, y left, radius, end Circle x coordinate, y coordinate, radius)

8) Usage mode

The pattern is actually a duplicate of the image, calling the method Createpattern (image element, CSS background-repeat value), assigning the returned object to FillStyle ()

    

The first argument to Createpattern can also be a video object or a canvas object

9) Get Image data

Call the method Getimagedata (the x-coordinate of the obtained image area, y-coordinate, width,height), return the ImageData object, which has three properties: Width,height,data. Where the Data property stores the value of each pixel in the image, and each pixel holds the Rgba four element values.

var data = Context.getimagedata (0,0,image.width,image.height);

Red = data[0]

Gree = data[1]

Blue = data[2]

Alpha = data[3]

10) Synthesis

Two properties: Globalalpha = 0 to 1 value, Globalcompositionoperation = specified string value.

Globalalpha setting transparency for all painted areas

globalcompositionoperation specifies how the graph drawn first overlaps with the drawing after.

    

  

javascript: Drawing 2D graphics with 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.