Canvas ., Canvas basic usage.

Source: Internet
Author: User

Canvas ., Canvas basic usage.

Directory:

Create a canvas.

Draw straight lines, polygon, and jigsaw puzzle.

Draw an arc and a circle.

(Some images are too wide and squeezed out. You can go to the album [image used by canvas .] View the source image .)

 

Create a canvas.

HTML5 new tag <canvas> </canvas>

The id is added during use and the canvas element is obtained through the id to perform the Drawing operation.

<canvas id="canvas"></canvas>

You can add styles. When the width is not specified, the default value is 300px * 150px.

<canvas id="canvas" style="border:1px solid #aaa;display:block;margin:50px auto;"></canvas>

The size of the specified canvas is determined by the width and height attributes of the canvas label, instead of the CSS attribute, and there is no unit at the time.

<canvas id="canvas" width="1024" height="768"></canvas>

Use JavaScript to obtain the canvas and getContext to obtain the context of the drawing.

Var canvas = document. getElementById ('canvas '); var context = canvas. getContext ('2d'); // draw with context

In addition to the canvas size specified in the label, you can also specify the canvas size in JS.

canvas.width=1024;canvas.height=768;

If the browser does not support canvas, you can use either of the following methods.

<Canvas> the current browser does not support canvas. Change the browser and try again. </Canvas>

(When the browser supports canvas, the content of the canvas label will be ignored by the browser)

Or

Var canvas = document. getElementById ("canvas"); if (canvas. getContext ("2d") {var context = canvas. getContext ("2d");} else {alert ("the current browser does not support canvas. Please change the browser and try again. ")}

Used content:

Canvas. width

Canvas. height

Canvas. getContext ()

 

Draw straight lines, polygon, and jigsaw puzzle.
context.moveTo(100,100);context.lineTo(200,200);context.stroke();

These three lines of code can be used to draw a straight line.

MoveTo, which is equivalent to placing the pen strokes at the coordinates of 100,100. LineTo is the position from 100,100 to 200,200. At this time, the line has not been drawn, and the context. stroke () method is used to draw the line. (The coordinates here are relative to <canvas>. The upper left corner of <canvas> is the coordinate origin .)

Both moveTo and lineTo are painting status settings, while stroke () is painting.

In addition to moveTo, lineTo status settings. Also:

LineWidth. The width of the line.

StrokeStyle. Line style (color), string format.

context.lineWidth = 5;context.strokeStyle = 'blue';

Write status before writing and drawing.

Draw multiple line segments. You only need to connect lineTo.

context.lineTo(100,200);

When the coordinates of the last lineTo () are the same as those of moveTo (), a polygon can be connected at the beginning and end.

context.lineTo(100,100);

The same is true for rectangle, trapezoid, and five-star shapes.

Stroke () is mainly used to draw lines.

 

Color the polygon. Status: fillStyle. Draw method: fill ()

context.fillStyle = 'rgb(30,60,90)';context.fill();

Draw the path and color it:

var canvas = document.getElementById('canvas');canvas.width = 300;canvas.height = 300;var context = canvas.getContext('2d');
context.moveTo(100,100);context.lineTo(200,200);context.lineTo(100,200);context.lineTo(100,100);context.fillStyle = 'rgb(30,60,90)';context.fill();context.lineWidth = 5;context.strokeStyle = 'blue';context.stroke();

When drawing the second line segment/polygon, you only need to call moveTo () again ().

context.moveTo(200,100);context.lineTo(250,250);context.strokeStyle = 'red';context.stroke();

Q: Why are the two lines of the same color and width?

Answer: canvas is drawn based on the state. When the stroke () method of the second line segment is called, The State of the first line segment still works, (The triangle and the second line segment are drawn), and The strokeStyle of the second line segment overwrites the strokeStyle of the first line segment.

 

Separate the statuses of two line segments by calling movinpath () before the defined path (moveTo ). Correspondingly, closePath () is used after the path is defined ().

Used content:

Context. moveTo (x1, y1)

Context. lineTo (x2, y2)

 

Context. beginPath ()

Context. closePath ()

 

Context. lineWidth

Context. strokeStyle

Context. fillStyle

 

Context. stroke ()

Context. fill ()

 

Draw a jigsaw puzzle.

<Canvas id = "canvas" style = "border: 1px solid # aaa; display: block; margin: 50px auto;"> the current browser does not support canvas. Change the browser and try again. </Canvas>
var tangram = [        {p:[{x:0,y:0},{x:800,y:0},{x:400,y:400}],color:'red'},    {p:[{x:0,y:0},{x:400,y:400},{x:0,y:800}],color:'orange'},    {p:[{x:800,y:0},{x:800,y:400},{x:600,y:600},{x:600,y:200}],color:'yellow'},    {p:[{x:600,y:200},{x:600,y:600},{x:400,y:400}],color:'green'},    {p:[{x:400,y:400},{x:600,y:600},{x:400,y:800},{x:200,y:600}],color:'lightblue'},    {p:[{x:200,y:600},{x:400,y:800},{x:0,y:800}],color:'blue'},    {p:[{x:800,y:400},{x:800,y:800},{x:400,y:800}],color:'purple'}]window.onload = function(){    var canvas = document.getElementById('canvas');    canvas.width = 800;    canvas.height = 800;    var context = canvas.getContext('2d');    for(var i=0;i<tangram.length;i++){        draw(tangram[i],context);    }}function draw( piece , ctx ){    ctx.beginPath();    ctx.moveTo(piece.p[0].x,piece.p[0].y);    for(var i=1;i<piece.p.length;i++){        ctx.lineTo(piece.p[i].x,piece.p[i].y);    }    ctx.closePath();    ctx.fillStyle = piece.color;    ctx.fill();    ctx.strokeStyle = 'pink';    ctx.lineWidth = 3;    ctx.stroke();}

 

Draw an arc and a circle.
context.arc(x,y,radius,startingAngle,endingAngle,anticlockwise=false)

Draw an arc. The parameters are the coordinates of the center x, y, radius of the circle, radians of the start, radians of the end, clockwise or counterclockwise (false indicates clockwise rotation, true indicates clockwise rotation ).

Radian/angle.

The radians remain unchanged regardless of clockwise or counterclockwise.

The following is a clockwise angle.

Draw 3/4 circles. Arc () is also a status setting. When the last parameter is left blank, the default value is false, that is, clockwise.

Context. lineWidth = 5; context. strokeStyle = 'blue'; context. arc (150,150,100, 0, 1.5 * Math. PI); // center (150,150), radius 100, from 0 radian to 1.5PI radian. Context. stroke ();

When the last parameter is set to true.

context.arc(150,150,100,0,1.5*Math.PI,true);

 

Draw Multiple Arc segments.

context.lineWidth = 5;context.strokeStyle= 'blue';for(var i=0;i<10;i++){    context.beginPath();    context.arc(50+i*100,60,40,0,2*Math.PI*(i+1)/10);    context.closePath();    context.stroke();}

Q: Why is a straight line connecting the beginning and end of the arc?

Answer: This is another function of closePath. When closePath () is used when the currently drawn path is not a closed path, the unclosed path is automatically connected by a line at the beginning and end.

 

The above code will not be connected at the beginning or end without using closePath:

Use closePath () and draw in a counter-clockwise direction:

Do not use closePath (), and draw in the clockwise direction:

Fill processing. Change strokeStyle to fillStyle. Change stroke () to fill (). And closePath () effect:

Remove closePath ():

Note: closePath () does not work for fill. When fill () is called, no matter whether you call closePath () or not, the unclosed content is automatically added to the beginning, end, and end of the content.

Used content:

Context. arc (x, y, radius, startingAngle, endingAngle, anticlockwise = false)

Related Article

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.