HTML Canvas 学习笔记

﹏ヽ暗。殇╰゛Y 2022-09-02 14:44 279阅读 0赞

























































































































































































     
  Colors, Styles, and Shadows Property  
fillStyle strokeStyle shadowColor
shadowBlur shadowOffsetX shadowOffsetY
  Colors, Styles, and Shadows Method  
createLinearGradient() createPattern() createRadialGradient()
addColorStop()    
  Line Styles Property  
lineCap lineJoin lineWidth
miterLimit    
  Rectangles Method  
rect() fillRect() strokeRect()
clearRect()    
  Paths Method  
fill() stroke() beginPath()
moveTo() closePath() lineTo()
clip() quadraticCurveTo() bezierCurveTo()
arc() arcTo() isPointInPath()
  Transformations Method  
scale() rotate() translate()
transform() setTransform()  
  Text Property  
font textAlign textBaseline
  Text Method  
fillText() strokeText() measureText()
  Image Drawing Method  
drawImage()    
  Pixel Manipulation Property  
width height data
  Pixel Manipulation Method  
createImageData() getImageData() putImageData()
  Compositing Property  
globalAlpha globalCompositeOperation  
  Other Method  
save() restore() getContext()
toDataURL()    

Reference

  • Link 1
  • Link 2

Description

The HTML5 tag is used to draw graphics, on the fly, via scripting (usually JavaScript).

However, the element has no drawing abilities of its own (it is only a container for graphics) - you must use a script to actually draw the graphics.

The getContext() method returns an object that provides methods and properties for drawing on the canvas.

This reference will cover the properties and methods of the getContext(“2d”) object, which can be used to draw text, lines, boxes, circles, and more - on the canvas.

Browser Support

Internet Explorer 9, Firefox, Opera, Chrome, and Safari support and its properties and methods.

Note: Internet Explorer 8 and earlier versions, do not support the element.

Colors, Styles, and Shadows


































Property Description
fillStyle Sets or returns the color, gradient, or pattern used to fill the drawing
strokeStyle Sets or returns the color, gradient, or pattern used for strokes
shadowColor Sets or returns the color to use for shadows
shadowBlur Sets or returns the blur level for shadows
shadowOffsetX Sets or returns the horizontal distance of the shadow from the shape
shadowOffsetY Sets or returns the vertical distance of the shadow from the shape

























Method Description
createLinearGradient() Creates a linear gradient (to use on canvas content)
createPattern() Repeats a specified element in the specified direction
createRadialGradient() Creates a radial/circular gradient (to use on canvas content)
addColorStop() Specifies the colors and stop positions in a gradient object

Property

fillStyle

Sets or returns the color, gradient, or pattern used to fill the drawing

gradient
英 [ˈɡreɪdiənt] 美 [ˈɡreɪdiənt]
n. (尤指公路或铁路的)坡度,斜率,倾斜度; (温度、压力等的)变化率,梯度变化曲线

Definition and Usage

The fillStyle property sets or returns the color, gradient, or pattern used to fill the drawing.


















Default value: #000000
JavaScript syntax: context.fillStyle=color|gradient|pattern;
Property Values





















Value Description
color A CSS color value that indicates the fill color of the drawing. Default value is #000000
gradient A gradient object (linear or radial) used to fill the drawing
pattern A pattern object to use to fill the drawing
Example
1 Define a red fill-color for the rectangle

797a349b57d08f81b79716137b68c13b.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.fillStyle="#FF0000";
  4. ctx.fillRect(20,20,150,100);
2 Define a gradient (top to bottom) as the fill style for the rectangle

855260508fb2f57b022b10dba8f6b5c5.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. var my_gradient=ctx.createLinearGradient(0,0,0,170);
  4. my_gradient.addColorStop(0,"black");
  5. my_gradient.addColorStop(1,"white");
  6. ctx.fillStyle=my_gradient;
  7. ctx.fillRect(20,20,150,100);
3 Define a gradient (left to right) as the fill style for the rectangle

ab201653f7fb5b9d5c66e3163c6c14cb.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. var my_gradient=ctx.createLinearGradient(0,0,170,0);
  4. my_gradient.addColorStop(0,"black");
  5. my_gradient.addColorStop(1,"white");
  6. ctx.fillStyle=my_gradient;
  7. ctx.fillRect(20,20,150,100);
4 Define a gradient that goes from black, to red, to white, as the fill style for the rectangle

d843f4af3f771828eb2f8c6d77532b48.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. var my_gradient=ctx.createLinearGradient(0,0,170,0);
  4. my_gradient.addColorStop(0,"black");
  5. my_gradient.addColorStop(0.5,"red");
  6. my_gradient.addColorStop(1,"white");
  7. ctx.fillStyle=my_gradient;
  8. ctx.fillRect(20,20,150,100);
5 Use an image to fill the drawing

45a7c91ac8510ce94066cdc21862e7c5.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. var img=document.getElementById("lamp");
  4. var pat=ctx.createPattern(img,"repeat");
  5. ctx.rect(0,0,150,100);
  6. ctx.fillStyle=pat;
  7. ctx.fill();

strokeStyle

Sets or returns the color, gradient, or pattern used for strokes

stroke
英 [strəʊk] 美 [stroʊk]
n. (打、击等的)一下;击球(动作);一击;划水动作;划桨动作
vt. 轻抚(动物的毛皮);抚摩(物体表面或头发等);轻挪;轻触;轻拭

Definition and Usage

The strokeStyle property sets or returns the color, gradient, or pattern used for strokes.


















Default value: #000000
JavaScript syntax: context.strokeStyle=color|gradient|pattern;
Property Values





















Value Description
color A CSS color value that indicates the stroke color of the drawing. Default value is #000000
gradient A gradient object (linear or radial) used to create a gradient stroke
pattern A pattern object used to create a pattern stroke
Example
1 Use a stroke color of red to draw a rectangle.

1860b07b81e7ba445bcc4c54d6ab0fd6.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.strokeStyle="#FF0000";
  4. ctx.strokeRect(20,20,150,100);
2 Use a gradient stroke to draw a rectangle.

c3cc089805318b005826845b86bda4ca.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. var gradient=ctx.createLinearGradient(0,0,170,0);
  4. gradient.addColorStop("0","magenta");
  5. gradient.addColorStop("0.5","blue");
  6. gradient.addColorStop("1.0","red");
  7. // Fill with gradient
  8. ctx.strokeStyle=gradient;
  9. ctx.lineWidth=5;
  10. ctx.strokeRect(20,20,150,100);
3 Write the text “Big smile!” with a gradient stroke

b309b7ba89430eb938e39976c34d59c3.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.font="30px Verdana";
  4. // Create gradient
  5. var gradient=ctx.createLinearGradient(0,0,c.width,0);
  6. gradient.addColorStop("0","magenta");
  7. gradient.addColorStop("0.5","blue");
  8. gradient.addColorStop("1.0","red");
  9. // Fill with gradient
  10. ctx.strokeStyle=gradient;
  11. ctx.strokeText("Big smile!",10,50);

shadowColor

Sets or returns the color to use for shadows

Definition and Usage

The shadowColor property sets or returns the color to use for shadows.

Note: Use the shadowColor property together with the shadowBlur property to create a shadow.

Tip: Adjust the shadow by using the shadowOffsetX and shadowOffsetY properties.


















Default value: #000000
JavaScript syntax: context.shadowColor=color;
Property Values













Value Description
color The CSS color value to use for shadows. Default value is #000000
Example
1 Draw a red rectangle with a black shadow

89bc2f091419fe4622503d7cb8f958df.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.shadowBlur=20;
  4. ctx.shadowColor="black";
  5. ctx.fillStyle="red";
  6. ctx.fillRect(20,20,100,80);

shadowBlur

Sets or returns the blur level for shadows

Definition and Usage

The shadowBlur property sets or returns the blur level for shadows.


















Default value: 0
JavaScript syntax: context.shadowBlur=number;
Property Values













Value Description
number The blur level for the shadow
Example
1 Draw a red rectangle with a black shadow, with blur level of 20

89bc2f091419fe4622503d7cb8f958df.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.shadowBlur=20;
  4. ctx.shadowColor="black";
  5. ctx.fillStyle="red";
  6. ctx.fillRect(20,20,100,80);

shadowOffsetX

Sets or returns the horizontal distance of the shadow from the shape

Definition and Usage

The shadowOffsetX property sets or returns the horizontal distance of the shadow from the shape.

  • shadowOffsetX=0 indicates that the shadow is right behind the shape.
  • shadowOffsetX=20 indicates that the shadow starts 20 pixels to the right (from the shape’s left position).
  • shadowOffsetX=-20 indicates that the shadow starts 20 pixels to the left (from the shape’s left position).

Tip: To adjust the vertical distance of the shadow from the shape, use the shadowOffsetY property.


















Default value: 0
JavaScript syntax: context.shadowOffsetX=number;
Property Values













Value Description
number A positive or negative number that defines the horizontal distance of the shadow from the shape
Example
1 Draw a rectangle with a shadow placed 20/100 pixels to the right (from the rectangle’s left position)

7c648ec3bd25064fb7ce186c5b5bd1eb.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.shadowBlur=10;
  4. ctx.shadowOffsetX=20;
  5. ctx.shadowColor="black";
  6. ctx.fillStyle="red";
  7. ctx.fillRect(20,20,100,80);

871a8cf7240ac8678b23dc21c4314346.png

  1. var c = document.getElementById("myCanvas");
  2. var ctx = c.getContext("2d");
  3. ctx.shadowBlur = 10;
  4. ctx.shadowOffsetX = 100;
  5. ctx.shadowColor = "black";
  6. ctx.fillStyle= "red";
  7. ctx.fillRect(20, 20, 100, 80);

shadowOffsetY

Sets or returns the vertical distance of the shadow from the shape

Definition and Usage

The shadowOffsetY property sets or returns the vertical distance of the shadow from the shape.

  • shadowOffsety=0 indicates that the shadow is right behind the shape.
  • shadowOffsetY=20 indicates that the shadow starts 20 pixels below the shape’s top position.
  • shadowOffsetY=-20 indicates that the shadow starts 20 pixels above the shape’s top position.

Tip: To adjust the horizontal distance of the shadow from the shape, use the shadowOffsetX property.


















Default value: 0
JavaScript syntax: context.shadowOffsetY=number;
Property Values













Value Description
number A positive or negative number that defines the vertical distance of the shadow from the shape
Example
1 Draw a rectangle with a shadow placed 20 pixels below the rectangle’s top position

2fbe17d971893f44602dbd82bfd41e8e.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.shadowBlur=10;
  4. ctx.shadowOffsetY=20;
  5. ctx.shadowColor="black";
  6. ctx.fillStyle="red";
  7. ctx.fillRect(20,20,100,80);

Method

createLinearGradient()

Definition and Usage

The createLinearGradient() method creates a linear gradient object.

The gradient can be used to fill rectangles, circles, lines, text, etc.

Tip: Use this object as the value to the strokeStyle or fillStyle properties.

Tip: Use the addColorStop() method to specify different colors, and where to position the colors in the gradient object.














JavaScript syntax: context.createLinearGradient(x0,y0,x1,y1);
Parameter Values

























Parameter Description
x0 The x-coordinate of the start point of the gradient
y0 The y-coordinate of the start point of the gradient
x1 The x-coordinate of the end point of the gradient
y1 The y-coordinate of the end point of the gradient
Example

查阅前文的fillStyle的Example 2、3、4,strokeStyle的Example 2。

createPattern()

Definition and Usage

The createPattern() method repeats the specified element in the specified direction.

The element can be an image, video, or another element.

The repeated element can be used to draw/fill rectangles, circles, lines etc.














JavaScript syntax: context.createPattern(image,“repeat|repeat-x|repeat-y|no-repeat”);
Parameter Values





























Parameter Description
image Specifies the image, canvas, or video element of the pattern to use
repeat Default. The pattern repeats both horizontally and vertically
repeat-x The pattern repeats only horizontally
repeat-y The pattern repeats only vertically
no-repeat The pattern will be displayed only once (no repeat)
Example

查阅前文的fillStyle的Example 5

当参数为repeat:

dd5e2b2e0f5f6d2ac956265ea1e2f376.png

当参数为repeat-x:

097123a5ab41ce258309b84a3e4d9c23.png

当参数为repeat-y:

b0dec48cb83dc6a57bf5289a9251bfc8.png

当参数为no-repeat:

c9cf1d06f0fcf99b67bdb16eddff3939.png

createRadialGradient()

Definition and Usage

The createRadialGradient() method creates a radial/circular gradient object.

The gradient can be used to fill rectangles, circles, lines, text, etc.

Tip: Use this object as the value to the strokeStyle or fillStyle properties.

Tip: Use the addColorStop() method to specify different colors, and where to position the colors in the gradient object.














JavaScript syntax: context.createRadialGradient(x0,y0,r0,x1,y1,r1);
Parameter Values

































Parameter Description
x0 The x-coordinate of the starting circle of the gradient
y0 The y-coordinate of the starting circle of the gradient
r0 The radius of the starting circle
x1 The x-coordinate of the ending circle of the gradient
y1 The y-coordinate of the ending circle of the gradient
r1 The radius of the ending circle
Example
1 Draw a rectangle and fill with a radial/circular gradient:

812093d54c9bb313ffc5bcf6d427149e.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. var grd=ctx.createRadialGradient(75,50,5,90,60,100);
  4. grd.addColorStop(0,"red");
  5. grd.addColorStop(1,"white");
  6. // Fill with gradient
  7. ctx.fillStyle=grd;
  8. ctx.fillRect(10,10,150,100);

addColorStop()

Definition and Usage

The addColorStop() method specifies the colors and position in a gradient object.

The addColorStop() method is used together with createLinearGradient() or createRadialGradient().

Note: You can call the addColorStop() method multiple times to change a gradient. If you omit this method for gradient objects, the gradient will not be visible. You need to create at least one color stop to have a visible gradient.














JavaScript syntax: gradient.addColorStop(stop,color);
Parameter Values

















Parameter Description
stop A value between 0.0 and 1.0 that represents the position between start and end in a gradient
color A CSS color value to display at the stop position
Example
1 Define a gradient with multiple addColorStop() methods

25279418ea7cd0840d63c3f8b2e4c74a.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. var grd=ctx.createLinearGradient(0,0,170,0);
  4. grd.addColorStop(0,"black");
  5. grd.addColorStop(0.3,"magenta");
  6. grd.addColorStop(0.5,"blue");
  7. grd.addColorStop(0.6,"green");
  8. grd.addColorStop(0.8,"yellow");
  9. grd.addColorStop(1,"red");
  10. ctx.fillStyle=grd;
  11. ctx.fillRect(20,20,150,100);

Line Styles


























Property Description
lineCap Sets or returns the style of the end caps for a line
lineJoin Sets or returns the type of corner created, when two lines meet
lineWidth Sets or returns the current line width
miterLimit Sets or returns the maximum miter length

Property

lineCap

Sets or returns the style of the end caps for a line

Definition and Usage

The lineCap property sets or returns the style of the end caps for a line.

Note: The value “round” and “square” make the lines slightly longer.


















Default value: butt
JavaScript syntax: context.lineCap=“butt|round|square”;
Property Values





















Value Description
butt Default. A flat edge is added to each end of the line
round A rounded end cap is added to each end of the line
square A square end cap is added to each end of the line
Example
1 Draw a line with end caps

e5714fd6a40882f16d7bbb0e4067dce5.png

  1. var c = document.getElementById("myCanvas");
  2. var ctx = c.getContext("2d");
  3. ctx.beginPath();
  4. ctx.lineWidth = 10;
  5. ctx.lineCap = "butt";
  6. ctx.moveTo(20, 20);
  7. ctx.lineTo(200, 20);
  8. ctx.stroke();
  9. ctx.beginPath();
  10. ctx.lineCap = "round";
  11. ctx.moveTo(20, 40);
  12. ctx.lineTo(200, 40);
  13. ctx.stroke();
  14. ctx.beginPath();
  15. ctx.lineCap = "square";
  16. ctx.moveTo(20, 60);
  17. ctx.lineTo(200, 60);
  18. ctx.stroke();

lineJoin

Sets or returns the type of corner created, when two lines meet

Definition and Usage

The lineJoin property sets or returns the type of corner created, when two lines meet.

Note: The “miter” value is affected by the miterLimit property.


















Default value: miter
JavaScript syntax: context.lineJoin=“bevel|round|miter”;
Property Values





















Value Description
bevel Creates a beveled corner
round Creates a rounded corner
miter Default. Creates a sharp corner

bevel
英 [ˈbevl] 美 [ˈbevl]
n. 斜边;斜面;斜角规
v. 把(物体的方形边)改成斜面边

miter
英 [ˈmaɪtə®] 美 [ˈmaɪtər]
n. 主教法冠;斜接
v. 给主教等加冠;使斜接

Example
1 Create a different corner when the two lines meet

1679f31faccb84015b731882a8af9e37.png

  1. var c = document.getElementById("myCanvas");
  2. var ctx = c.getContext("2d");
  3. ctx.beginPath();
  4. ctx.lineWidth = 10;
  5. ctx.lineJoin = "round";//<---------------
  6. ctx.moveTo(20, 20);
  7. ctx.lineTo(100, 50);
  8. ctx.lineTo(20, 100);
  9. ctx.stroke();
  10. ctx = c.getContext("2d");
  11. ctx.beginPath();
  12. ctx.lineWidth = 10;
  13. ctx.lineJoin = "miter";//<--------------- Default. Creates a sharp corner
  14. ctx.moveTo(20, 150);
  15. ctx.lineTo(100, 180);
  16. ctx.lineTo(20, 230);
  17. ctx.stroke();
  18. ctx = c.getContext("2d");
  19. ctx.beginPath();
  20. ctx.lineWidth = 10;
  21. ctx.lineJoin = "bevel";//<--------------- 类似条形纸条斜折效果
  22. ctx.moveTo(20, 280);
  23. ctx.lineTo(100, 310);
  24. ctx.lineTo(20, 360);
  25. ctx.stroke();

lineWidth

Sets or returns the current line width

Definition and Usage

The lineWidth property sets or returns the current line width, in pixels.


















Default value: 1
JavaScript syntax: context.lineWidth=number;
Property Values













Value Description
number The current line width, in pixels
Example

参考上文lineJoin的例子

miterLimit

Sets or returns the maximum miter length

Definition and Usage

The miterLimit property sets or returns the maximum miter length.

The miter length is the distance between the inner corner and the outer corner where two lines meet.

Miter Limit figure 1

Tip: The miterLimit property works only if the lineJoin attribute is “miter”.

The miter length grows bigger as the angle of the corner gets smaller.

To prevent the miter length from being too long, we can use the miterLimit property.

If the miter length exceeds the miterLimit value, the corner will be displayed as lineJoin type “bevel” (类似条形纸条斜折效果)(Fig 3):

Miter Limit figure 2


















Default value: 10
JavaScript syntax: context.miterLimit=number;
Property Values













Value Description
number A positive number that specifies the maximum miter length. If the current miter length exceeds the miterLimit, the corner will display as lineJoin “bevel”
Example
1 Draw lines with the maximum miter length of 5

69a7d31cd689decd28b7a3d3e447369c.png

  1. var c = document.getElementById("myCanvas");
  2. var ctx = c.getContext("2d");
  3. ctx.lineWidth = 10;
  4. ctx.lineJoin = "miter";
  5. ctx.miterLimit = 5;
  6. ctx.moveTo(20, 20);
  7. ctx.lineTo(50, 27);
  8. ctx.lineTo(20, 34);
  9. ctx.stroke();
  10. /* set the miterLimit to 4 (then, the miter length will exceed the miter limit), and when the lines meet it will be displayed as lineJoin="bevel". */
  11. ctx = c.getContext("2d");
  12. ctx.lineWidth = 10;
  13. ctx.lineJoin = "miter";
  14. ctx.miterLimit = 4;
  15. ctx.moveTo(20, 50);
  16. ctx.lineTo(50, 57);
  17. ctx.lineTo(20, 64);
  18. ctx.stroke();

Rectangles

Method


























Method Description
rect() Creates a rectangle
fillRect() Draws a “filled” rectangle
strokeRect() Draws a rectangle (no fill)
clearRect() Clears the specified pixels within a given rectangle

rect()

Creates a rectangle

Definition and Usage

The rect() method creates a rectangle.

Tip: Use the stroke()or the fill() method to actually draw the rectangle on the canvas.














JavaScript syntax: context.rect(x,y,width,height);
Parameter Values

























Parameter Description
x The x-coordinate of the upper-left corner of the rectangle
y The y-coordinate of the upper-left corner of the rectangle
width The width of the rectangle, in pixels
height The height of the rectangle, in pixels
Example
1 Create three rectangles with the rect() method

4a69804530bd7bd85733b8b09e61075b.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. // Red rectangle
  4. ctx.beginPath();
  5. ctx.lineWidth="6";
  6. ctx.strokeStyle="red";
  7. ctx.rect(5,5,290,140);
  8. ctx.stroke();
  9. // Green rectangle
  10. ctx.beginPath();
  11. ctx.lineWidth="4";
  12. ctx.strokeStyle="green";
  13. ctx.rect(30,30,50,50);
  14. ctx.stroke();
  15. // Blue rectangle
  16. ctx.beginPath();
  17. ctx.lineWidth="10";
  18. ctx.strokeStyle="blue";
  19. ctx.rect(50,50,150,80);
  20. ctx.stroke();

fillRect()

Draws a “filled” rectangle

Definition and Usage

The fillRect() method draws a “filled” rectangle. The default color of the fill is black.

Tip: Use the fillStyle property to set a color, gradient, or pattern used to fill the drawing.














JavaScript syntax: context.fillRect(x,y,width,height);
Parameter Values

























Parameter Description
x The x-coordinate of the upper-left corner of the rectangle
y The y-coordinate of the upper-left corner of the rectangle
width The width of the rectangle, in pixels
height The height of the rectangle, in pixels
Example
1 Draw a filled 150*100 pixels rectangle

accce9c455392c9b9678edb14010a924.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.fillRect(20,20,150,100);

strokeRect()

Draws a rectangle (no fill)

Definition and Usage

The strokeRect() method draws a rectangle (no fill). The default color of the stroke is black.

Tip: Use the strokeStyle property to set a color, gradient, or pattern to style the stroke.














JavaScript syntax: context.streRect(x,y,width,height);
Parameter Values

























Parameter Description
x The x-coordinate of the upper-left corner of the rectangle
y The y-coordinate of the upper-left corner of the rectangle
width The width of the rectangle, in pixels
height The height of the rectangle, in pixels
Example
1 Draw a 150*100 pixels rectangle

d2434167bc0a7f8f190ef67009af09dd.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.strokeRect(20,20,150,100);

clearRect()

Clears the specified pixels within a given rectangle

Definition and Usage

The clearRect() method clears the specified pixels within a given rectangle.














JavaScript syntax: context.clearRect(x,y,width,height);
Parameter Values

























Parameter Description
x The x-coordinate of the upper-left corner of the rectangle to clear
y The y-coordinate of the upper-left corner of the rectangle to clear
width The width of the rectangle to clear, in pixels
height The height of the rectangle to clear, in pixels
Example
1 Clear a rectangle within a given rectangle

855949fbd84c2a0188c711b44e39ce16.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.fillStyle="red";
  4. ctx.fillRect(0,0,300,150);
  5. ctx.clearRect(20,20,100,50);

Paths


























































Method Description
fill() Fills the current drawing (path)
stroke() Actually draws the path you have defined
beginPath() Begins a path, or resets the current path
moveTo() Moves the path to the specified point in the canvas, without creating a line
closePath() Creates a path from the current point back to the starting point
lineTo() Adds a new point and creates a line to that point from the last specified point in the canvas
clip() Clips a region of any shape and size from the original canvas
quadraticCurveTo() Creates a quadratic Bézier curve
bezierCurveTo() Creates a cubic Bézier curve
arc() Creates an arc/curve (used to create circles, or parts of circles)
arcTo() Creates an arc/curve between two tangents
isPointInPath() Returns true if the specified point is in the current path, otherwise false

Method

fill()

Fills the current drawing (path)

Definition and Usage

The fill() method fills the current drawing (path). The default color is black.

Tip: Use the fillStyle property to fill with another color/gradient.

Note: If the path is not closed, the fill() method will add a line from the last point to the startpoint of the path to close the path (like closePath()), and then fill the path.














JavaScript syntax: context.fill();
Example
1 Draw two 150*100 pixels rectangles. Fill one with a red color and the other with a blue color

231e4abaa664c13e01220e4dc3d11bf8.png

  1. var c = document.getElementById("myCanvas");
  2. var ctx = c.getContext("2d");
  3. ctx.beginPath();
  4. ctx.rect(20, 20, 150, 100);
  5. ctx.fillStyle = "red";
  6. ctx.fill();
  7. ctx.beginPath();
  8. ctx.rect(40, 40, 150, 100);
  9. ctx.fillStyle = "blue";
  10. ctx.fill();

stroke()

Actually draws the path you have defined

stroke

英 [strəʊk] 美 [stroʊk]

n. (打、击等的)一下;击球(动作);一击;划水动作;划桨动作;中风

vt. 轻抚(动物的毛皮);抚摩(物体表面或头发等);轻挪;轻触;轻拭

Definition and Usage

The stroke() method actually draws the path you have defined with all those moveTo() and lineTo() methods. The default color is black.

Tip: Use the strokeStyle property to draw with another color/gradient.














JavaScript syntax: context.stroke();
Example
1 Draw a path, shaped as the letter L - in a red color

e788081d3d673d4367cbf4a27536231e.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.beginPath();
  4. ctx.moveTo(20,20);
  5. ctx.lineTo(20,100);
  6. ctx.lineTo(70,100);
  7. ctx.strokeStyle="red";
  8. ctx.stroke();

beginPath()

Begins a path, or resets the current path

Definition and Usage

The beginPath() method begins a path, or resets the current path.

Tip: Use moveTo(), lineTo(), quadricCurveTo(), bezierCurveTo(), arcTo(), and arc(), to create paths.

Tip: Use the stroke() method to actually draw the path on the canvas.














JavaScript syntax: context.beginPath();
Example
1 Draw two paths on the canvas; one green and one purple

d3c43aebc03de88929da97958b1a0d73.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.beginPath();
  4. ctx.lineWidth="5";
  5. ctx.strokeStyle="green"; // Green path
  6. ctx.moveTo(0,75);
  7. ctx.lineTo(250,75);
  8. ctx.stroke(); // Draw it
  9. ctx.beginPath();
  10. ctx.strokeStyle="purple"; // Purple path
  11. ctx.moveTo(50,0);
  12. ctx.lineTo(150,130);
  13. ctx.stroke(); // Draw it

moveTo()

Moves the path to the specified point in the canvas, without creating a line

Definition and Usage

The moveTo() method moves the path to the specified point in the canvas, without creating a line.

Tip: Use the stroke() method to actually draw the path on the canvas.














JavaScript syntax: context.moveTo(x,y);
Parameter Values

















Parameter Description
x The x-coordinate of where to move the path to
y The y-coordinate of where to move the path to
Example
1 Begin a path, move to position 0,0. Create a line to position 300,150

6e15f1fb16e449845f070a97b8072425.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.beginPath();
  4. ctx.moveTo(0,0);
  5. ctx.lineTo(300,150);
  6. ctx.stroke();

closePath()

Creates a path from the current point back to the starting point

Definition and Usage

The closePath() method creates a path from the current point back to the starting point.

Tip: Use the stroke() method to actually draw the path on the canvas.

Tip: Use the fill() method to fill the drawing (black is default). Use the fillStyle property to fill with another color/gradient.














JavaScript syntax: context.closePath();
Example
1 Draw a path, shaped as the letter L, and then draw a line back to the starting point

d468477ce1500704728abf547ab4c51b.png

  1. var c = document.getElementById("myCanvas");
  2. var ctx = c.getContext("2d");
  3. ctx.beginPath();
  4. ctx.moveTo(20, 20);
  5. ctx.lineTo(20, 100);
  6. ctx.lineTo(70, 100);
  7. ctx.closePath();
  8. ctx.stroke();
  9. ctx.beginPath();
  10. ctx.moveTo(20, 150);
  11. ctx.lineTo(20, 230);
  12. ctx.lineTo(70, 230);
  13. //ctx.closePath();//<----------注释掉ctx.closePath()
  14. ctx.stroke();

lineTo()

Adds a new point and creates a line to that point from the last specified point in the canvas

Definition and Usage

The lineTo() method adds a new point and creates a line TO that point FROM the last specified point in the canvas (this method does not draw the line).

Tip: Use the stroke() method to actually draw the path on the canvas.














JavaScript syntax: context.lineTo(x,y);
Parameter Values

















Parameter Description
x The x-coordinate of where to create the line to
y The y-coordinate of where to create the line to
Example

参考上文closePath()的Example。

clip()

Clips剪出 a region of any shape and size from the original canvas

clip
英 [klɪp] 美 [klɪp]
n. 夹子;修剪;(金属或塑料的)回形针;首饰别针;剪短
v. 夹住;别住;被夹住;剪(掉);修剪;碰撞(某物的边缘或侧面)

Definition and Usage

The clip() method clips a region of any shape and size from the original canvas.

Tip: Once a region is clipped, all future drawing will be limited to the clipped region (no access to other regions on the canvas). You can however save the current canvas region using the save() method before using the clip() method, and restore it (with the restore() method) any time in the future.














JavaScript syntax: context.clip();
Example
1 Clip of a rectangular region of 200*120 pixels from the canvas. Then, draw a red rectangle. Only the part of the red rectangle that is inside the clipped area is visible

e431d39a98fe3c26d7d7a12a832f5d9d.png

  1. <span>Without clip():</span>
  2. <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
  3. Your browser does not support the HTML5 canvas tag.</canvas>
  4. <script> var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); // Draw a rectangle ctx.rect(50, 20, 200, 120); ctx.stroke(); // Draw red rectangle ctx.fillStyle = "red"; ctx.fillRect(0, 0, 150, 100); </script>
  5. <span>With clip():</span>
  6. <canvas id="myCanvas2" width="300" height="150" style="border:1px solid #d3d3d3;">
  7. Your browser does not support the HTML5 canvas tag.</canvas>
  8. <script> var c = document.getElementById("myCanvas2"); var ctx = c.getContext("2d"); // Clip a rectangular area ctx.rect(50, 20, 200, 120); ctx.stroke(); ctx.clip(); // Draw red rectangle after clip() ctx.fillStyle = "red"; ctx.fillRect(0, 0, 150, 100); </script>

quadraticCurveTo()

Creates a quadratic Bézier curve

quadratic
英 [kwɒˈdrætɪk] 美 [kwɑːˈdrætɪk]
adj. 平方的;二次方的

贝塞尔曲线(Bézier curve),又称贝兹曲线或贝济埃曲线,是应用于二维图形应用程序的数学曲线。一般的矢量图形软件通过它来精确画出曲线,贝兹曲线由线段与节点组成,节点是可拖动的支点,线段像可伸缩的皮筋,我们在绘图工具上看到的钢笔工具就是来做这种矢量曲线的。贝塞尔曲线是计算机图形学中相当重要的参数曲线,在一些比较成熟的位图软件中也有贝塞尔曲线工具,如PhotoShop等。百度百科

Definition and Usage

The quadraticCurveTo() method adds a point to the current path by using the specified control points that represent a quadratic Bézier curve.

A quadratic Bézier curve requires two points. The first point is a control point that is used in the quadratic Bézier calculation and the second point is the ending point for the curve. The starting point for the curve is the last point in the current path. If a path does not exist, use the beginPath() and moveTo() to define a starting point.

A quadratic Bézier curve

  • Start point:

    • moveTo(20,20)
  • Control point:

    • quadraticCurveTo(20,100,200,20)
  • End point:

    • quadraticCurveTo(20,100,200,20)

Tip: Check out the bezierCurveTo() method. It has two control-points instead of one.














JavaScript syntax: context.quadraticCurveTo(cpx,cpy,x,y);
Parameter Values

























Parameter Description
cpx The x-coordinate of the Bézier control point
cpy The y-coordinate of the Bézier control point
x The x-coordinate of the ending point
y The y-coordinate of the ending point
Example
1 Draw a quadratic Bézier curve

9e4b98cf9cd8ce4a3cf10458a2993d47.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.beginPath();
  4. ctx.moveTo(20,20);
  5. ctx.quadraticCurveTo(20,100,200,20);
  6. ctx.stroke();

bezierCurveTo()

Creates a cubic Bézier curve

cubic
英 [ˈkjuːbɪk] 美 [ˈkjuːbɪk]
adj. 立方体的;立方的;用立方单位度量(或表示)的;立方形的

Definition and Usage

The bezierCurveTo() method adds a point to the current path by using the specified control points that represent a cubic Bézier curve.

A cubic bezier curve requires three points. The first two points are control points that are used in the cubic Bézier calculation and the last point is the ending point for the curve. The starting point for the curve is the last point in the current path. If a path does not exist, use the beginPath() and moveTo() methods to define a starting point.

A cubic bezier curve

  • Start point

    • moveTo(20,20)
  • Control point 1

    • bezierCurveTo(20,100,200,100,200,20)
  • Control point 2

    • bezierCurveTo(20,100,200,100,200,20)
  • End point

    • bezierCurveTo(20,100,200,100,200,20)

Tip: Check out the quadraticCurveTo() method. It has one control point instead of two.














JavaScript syntax: context.bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y);
Parameter Values

































Parameter Description
cp1x The x-coordinate of the first Bézier control point
cp1y The y-coordinate of the first Bézier control point
cp2x The x-coordinate of the second Bézier control point
cp2y The y-coordinate of the second Bézier control point
x The x-coordinate of the ending point
y The y-coordinate of the ending point
Example
1 Draw a cubic Bézier curve

1366dd53b2589d388552e14c9ead1677.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.beginPath();
  4. ctx.moveTo(20,20);
  5. ctx.bezierCurveTo(20,100,200,100,200,20);
  6. ctx.stroke();

arc()

Creates an arc/curve (used to create circles, or parts of circles)

arc
英 [ɑːk] 美 [ɑːrk]
n. 弧;弧形;电弧
vi. 作弧形运动;形成电弧

curve
英 [kɜːv] 美 [kɜːrv]
n. 曲线;弧线;曲面;弯曲;(投向击球员的)曲线球
v. (使)沿曲线运动;呈曲线形

Definition and Usage

The arc() method creates an arc/curve (used to create circles, or parts of circles).

Tip: To create a circle with arc(): Set start angle to 0 and end angle to 2*Math.PI.

Tip: Use the stroke() or the fill() method to actually draw the arc on the canvas.

An arc

  • Center

    • arc(100,75,50,0 * Math.PI,1.5 * Math.PI)
  • Start angle

    • arc(100,75,50,**0 * Math.PI ** ,1.5*Math.PI)
  • End angle

    • arc(100,75,50,0 * Math.PI,1.5 * Math.PI)













JavaScript syntax: context.arc(x,y,r,sAngle,eAngle,counterclockwise);
Parameter Values

































Parameter Description
x The x-coordinate of the center of the circle
y The y-coordinate of the center of the circle
r The radius of the circle
sAngle The starting angle, in radians (0 is at the 3 o’clock position of the arc’s circle)
eAngle The ending angle, in radians
counterclockwise Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise.

clockwise
英 [ˈklɒkwaɪz] 美 [ˈklɑːkwaɪz]
adv./adj.顺时针方向的;顺时针方向(的)

counterclockwise
英 [ˌkaʊntəˈklɒkwaɪz] 美 [ˌkaʊntərˈklɑːkwaɪz]
adj. 反时针方向的;逆时针方向的
adv. 逆时针方向地;自右向左地

Example
1 Create a circle

7a89d89f10dd66ad2ffaff83dbb7a068.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.beginPath();
  4. ctx.arc(100,75,50,0,2*Math.PI);
  5. ctx.stroke();

arcTo()

Creates an arc/curve between two tangents

tangent
英 [ˈtændʒənt] 美 [ˈtændʒənt]
n. 切线;正切

Definition and Usage

The arcTo() method creates an arc/curve between two tangents on the canvas.

Canvas arcto() diagram

Tip: Use the stroke() method to actually draw the arc on the canvas.














JavaScript syntax: context.arcTo(x1,y1,x2,y2,r);
Parameter Values





























Parameter Description
x1 The x-coordinate of the first tangent
y1 The y-coordinate of the first tangent
x2 The x-coordinate of the second tangent
y2 The y-coordinate of the second tangent
r The radius of the arc
Example
1 Create an arc between two tangents on the canvas

2045a92f4c0af65c0f8b41e6c8033f88.png

  1. var c = document.getElementById("myCanvas");
  2. var ctx = c.getContext("2d");
  3. ctx.beginPath();
  4. ctx.moveTo(20, 20); // Create a starting point
  5. ctx.lineTo(100, 20); // Create a horizontal line
  6. ctx.arcTo(150, 20, 150, 70, 50); // Create an arc
  7. ctx.lineTo(150, 120); // Continue with vertical line
  8. ctx.stroke(); // Draw it

isPointInPath()

Returns true if the specified point is in the current path, otherwise false

Definition and Usage

The isPointInPath() method returns true if the specified point is in the current path, otherwise false.














JavaScript syntax: context.isPointInPath(x,y);
Parameter Values

















Parameter Description
x The x-coordinate to test
y The y-coordinate to test
Example
1 Draw a rectangle if the point 20,50 is in the current path

c9d7cf0198bbfbf47be02aede7d3638a.png

  1. var c = document.getElementById("myCanvas");
  2. var ctx = c.getContext("2d");
  3. ctx.rect(20, 20, 150, 100);
  4. if (ctx.isPointInPath(20, 50)) {
  5. ctx.stroke();
  6. };

Transformations






























Method Description
scale() Scales the current drawing bigger or smaller
rotate() Rotates the current drawing
translate() Remaps the (0,0) position on the canvas
transform() Replaces the current transformation matrix for the drawing
setTransform() Resets the current transform to the identity matrix. Then runs transform()

Method

scale()

Scales the current drawing bigger or smaller

scale
英 [skeɪl] 美 [skeɪl]
n. 规模;(尤指与其他事物相比较时的)范围;程度;等级;级别;等级体系
vt. 攀登;到达…顶点;去鳞;刮除牙石

Definition and Usage

The scale() method scales the current drawing, bigger or smaller.

Note: If you scale a drawing, all future drawings will also be scaled. The positioning will also be scaled. If you scale(2,2); drawings will be positioned twice as far from the left and top of the canvas as you specify.














JavaScript syntax: context.scale(scalewidth,scaleheight);
Parameter Values

















Parameter Description
scalewidth Scales the width of the current drawing (1=100%, 0.5=50%, 2=200%, etc.)
scaleheight Scales the height of the current drawing (1=100%, 0.5=50%, 2=200%, etc.)
Example
1 Draw a rectangle, scale to 200%, draw rectangle again, scale to 200%, draw rectangle again, scale to 200%, draw rectangle again

5defeae06fdeb8f0cad78602ac6e1b0e.png

  1. var c = document.getElementById("myCanvas");
  2. var ctx = c.getContext("2d");
  3. ctx.strokeStyle="black";
  4. ctx.strokeRect(5, 5, 25, 15);
  5. ctx.strokeStyle="red";
  6. ctx.scale(2, 2);
  7. ctx.strokeRect(5, 5, 25, 15);
  8. ctx.strokeStyle="green";
  9. ctx.scale(2, 2);
  10. ctx.strokeRect(5, 5, 25, 15);
  11. ctx.strokeStyle="blue";
  12. ctx.scale(2, 2);
  13. ctx.strokeRect(5, 5, 25, 15);

rotate()

Rotates the current drawing

Definition and Usage

The rotate() method rotates the current drawing.

Note: The rotation will only affect drawings made AFTER the rotation is done.














JavaScript syntax: context.rotate(angle);
Parameter Values













Parameter Description
angle The rotation angle, in radians. To calculate from degrees to radians: degrees Math.PI/180. Example: to rotate 5 degrees, specify the following: 5 Math.PI/180
Example
1 Rotate the rectangle 20 degrees

6c0d9b3b825b3cb3ed8552a86cfe6e2c.png

  1. var c = document.getElementById("myCanvas");
  2. var ctx = c.getContext("2d");
  3. ctx.rotate(20 * Math.PI / 180);
  4. ctx.fillRect(50, 20, 100, 50);

translate()

Remaps the (0,0) position on the canvas

Definition and Usage

The translate() method remaps the (0,0) position on the canvas.

Note: When you call a method such as fillRect() after translate(), the value is added to the x- and y-coordinate values.

Illustration of the translate() method














JavaScript syntax: context.translate(x,y);
Parameter Values

Note: You can specify one or both parameters.


















Parameter Description
x The value to add to horizontal (x) coordinates
y The value to add to vertical (y) coordinates
Example
1 Draw a rectangle in position (10,10), set new (0,0) position to (70,70). Draw same rectangle again (notice that the rectangle now starts in position (80,80)

304c0b39e99ac13dc016ffb7127b31a3.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.fillRect(10,10,100,50);
  4. ctx.translate(70,70);
  5. ctx.fillRect(10,10,100,50);

transform()

Replaces the current transformation matrix for the drawing

Definition and Usage

Each object on the canvas has a current transformation matrix.

The transform() method replaces the current transformation matrix. It multiplies the current transformation matrix with the matrix described by:

[ a c e b d f 0 0 1 ] \left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right] ⎣⎡​ab0​cd0​ef1​⎦⎤​

In other words, the transform() method lets you scale, rotate, move, and skew the current context.

Note: The transformation will only affect drawings made after the transform() method is called.

Note: The transform() method behaves relatively to other transformations made by rotate(), scale(), translate(), or transform(). Example: If you already have set your drawing to scale by two, and the transform() method scales your drawings by two, your drawings will now scale by four.

Tip: Check out the setTransform() method, which does not behave relatively to other transformations.














JavaScript syntax: context.transform(a,b,c,d,e,f);
Parameter Values

































Parameter Description
a Scales the drawing horizontally
b Skew the the drawing horizontally
c Skew the the drawing vertically
d Scales the drawing vertically
e Moves the the drawing horizontally
f Moves the the drawing vertically
Example
1 Draw a rectangle, add a new transformation matrix with transform(), draw the rectangle again, add a new transformation matrix, then draw the rectangle again.

Notice that each time you call transform(), it builds on the previous transformation matrix

155c262d38988889d77c0641e2577083.png

  1. var c = document.getElementById("myCanvas");
  2. var ctx = c.getContext("2d");
  3. ctx.fillStyle = "yellow";
  4. ctx.fillRect(0, 0, 250, 100)
  5. ctx.transform(1, 0.5, -0.5, 1, 30, 10);
  6. ctx.fillStyle = "red";
  7. ctx.fillRect(0, 0, 250, 100);
  8. ctx.transform(1, 0.5, -0.5, 1, 30, 10);
  9. ctx.fillStyle = "blue";
  10. ctx.fillRect(0, 0, 250, 100);

setTransform()

Resets the current transform to the identity matrix. Then runs transform()

Definition and Usage

Each object on the canvas has a current transformation matrix.

The setTransform() method resets the current transform to the identity matrix, and then runs transform() with the same arguments.

In other words, the setTransform() method lets you scale, rotate, move, and skew the current context.

Note: The transformation will only affect drawings made after the setTransform method is called.














JavaScript syntax: context.transform(a,b,c,d,e,f);
Parameter Values

































Parameter Description
a Scales the drawing horizontally
b Skew the the drawing horizontally
c Skew the the drawing vertically
d Scales the drawing vertically
e Moves the the drawing horizontally
f Moves the the drawing vertically
Example
1 Draw a rectangle, reset and create a new transformation matrix with setTransform(), draw the rectangle again, reset and create a new transformation matrix, then draw the rectangle again.

Notice that each time you call setTransform(), it resets the previous transformation matrix and then builds the new matrix, so in the example below, the red rectangle is not shown, because it is under the blue rectangle.

b89e697954613414853fe2bf5548ebd5.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.fillStyle="yellow";
  4. ctx.fillRect(0,0,250,100)
  5. ctx.setTransform(1,0.5,-0.5,1,30,10);
  6. ctx.fillStyle="red";
  7. ctx.fillRect(0,0,250,100);
  8. ctx.setTransform(1,0.5,-0.5,1,30,10);
  9. ctx.fillStyle="blue";
  10. ctx.fillRect(0,0,250,100);

PS.对比上文的transform()的Example对比理解。

Text






















Property Description
font Sets or returns the current font properties for text content
textAlign Sets or returns the current alignment for text content
textBaseline Sets or returns the current text baseline used when drawing text





















Method Description
fillText() Draws “filled” text on the canvas
strokeText() Draws text on the canvas (no fill)
measureText() Returns an object that contains the width of the specified text

Property

font

Sets or returns the current font properties for text content

Definition and Usage

The font property sets or returns the current font properties for text content on the canvas.

The font property uses the same syntax as the CSS font property.


















Default value: 10px sans-serif
JavaScript syntax: context.font=“italic small-caps bold 12px arial”;
Property Values





















































Values Description
font-style Specifies the font style. Possible values: normal, italic, oblique
font-variant Specifies the font variant. Possible values:normal, small-caps
font-weight Specifies the font weight. Possible values:normal, bold, bolder, lighter, 100, 200, 300, 400, 500, 600, 700, 800, 900
font-size/line-height Specifies the font size and the line-height, in pixels
font-family Specifies the font family
caption Use the font captioned controls (like buttons, drop-downs, etc.)
icon Use the font used to label icons
menu Use the font used in menus (drop-down menus and menu lists)
message-box Use the font used in dialog boxes
small-caption Use the font used for labeling small controls
status-bar Use the fonts used in window status bar
Example
1 Write a 30px high text on the canvas, using the font “Arial”

0e9bf11006e4f0977557628ae9215804.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.font="30px Arial";
  4. ctx.fillText("Hello World",10,50);

textAlign

Sets or returns the current alignment for text content

align
英 [əˈlaɪn] 美 [əˈlaɪn]
v. 排列;校准;排整齐;(尤指)使成一条直线;使一致

Definition and Usage

The textAlign property sets or returns the current alignment for text content, according to the anchor point.

Normally, the text will START in the position specified, however, if you set textAlign=“right” and place the text in position 150, it means that the text should END in position 150.

Tip: Use the fillText() or the strokeText() method to actually draw and position the text on the canvas.














Default value: start
JavaScript syntax: context.textAlign=“center|end|left|right|start”;
Property Values





























Values Description
start Default. The text starts at the specified position
end The text ends at the specified position
center The center of the text is placed at the specified position
left The text starts at the specified position
right The text ends at the specified position
Example
1 Create a red line in position 150. Position 150 is the anchor point for all the text defined in the example below

Study the effect of each textAlign property value.

34e8ff454d42a583e2b772a3ac93b8a6.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. // Create a red line in position 150
  4. ctx.strokeStyle="red";
  5. ctx.moveTo(150,20);
  6. ctx.lineTo(150,170);
  7. ctx.stroke();
  8. ctx.font="15px Arial";
  9. // Show the different textAlign values
  10. ctx.textAlign="start";
  11. ctx.fillText("textAlign=start",150,60);
  12. ctx.textAlign="end";
  13. ctx.fillText("textAlign=end",150,80);
  14. ctx.textAlign="left";
  15. ctx.fillText("textAlign=left",150,100);
  16. ctx.textAlign="center";
  17. ctx.fillText("textAlign=center",150,120);
  18. ctx.textAlign="right";
  19. ctx.fillText("textAlign=right",150,140);

textBaseline

Sets or returns the current text baseline used when drawing text

Definition and Usage

The textBaseline property sets or returns the current text baseline used when drawing text.

The illustration below demonstrates the various baselines supported by the textBaseline attribute:

textBaseline illustration

Note: The fillText() and strokeText() methods will use the specified textBaseline value when positioning the text on the canvas.


















Default value: alphabetic
JavaScript syntax: context.textBaseline=“alphabetic|top|hanging|middle|ideographic|bottom”;
Property Values

































Values Description
alphabetic Default. The text baseline is the normal alphabetic baseline
top The text baseline is the top of the em square
hanging The text baseline is the hanging baseline
middle The text baseline is the middle of the em square
ideographic The text baseline is the ideographic baseline
bottom The text baseline is the bottom of the bounding box
Example
1 Draw a red line at y=100, then place each word at y=100 with different textBaseline values

f6c46eb2898d1d1ce7bd0777f2e1b94b.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. //Draw a red line at y=100
  4. ctx.strokeStyle="red";
  5. ctx.moveTo(5,100);
  6. ctx.lineTo(395,100);
  7. ctx.stroke();
  8. ctx.font="20px Arial"
  9. //Place each word at y=100 with different textBaseline values
  10. ctx.textBaseline="top";
  11. ctx.fillText("Top",5,100);
  12. ctx.textBaseline="bottom";
  13. ctx.fillText("Bottom",50,100);
  14. ctx.textBaseline="middle";
  15. ctx.fillText("Middle",120,100);
  16. ctx.textBaseline="alphabetic";
  17. ctx.fillText("Alphabetic",190,100);
  18. ctx.textBaseline="hanging";
  19. ctx.fillText("Hanging",290,100);

Method

fillText()

Draws “filled” text on the canvas

Definition and Usage

The fillText() method draws filled text on the canvas. The default color of the text is black.

Tip: Use the font property to specify font and font size, and use the fillStyle property to render the text in another color/gradient.














JavaScript syntax: context.fillText(text,x,y,maxWidth);
Parameter Values

























Parameter Description
text Specifies the text that will be written on the canvas
x The x coordinate where to start painting the text (relative to the canvas)
y The y coordinate where to start painting the text (relative to the canvas)
maxWidth Optional. The maximum allowed width of the text, in pixels
Example
1 Write “Hello world!” and “Big smile!” (with gradient) on the canvas, using fillText()

19565d1538970634464980c709e0b85a.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.font="20px Georgia";
  4. ctx.fillText("Hello World!",10,50);
  5. ctx.font="30px Verdana";
  6. // Create gradient
  7. var gradient=ctx.createLinearGradient(0,0,c.width,0);
  8. gradient.addColorStop("0","magenta");
  9. gradient.addColorStop("0.5","blue");
  10. gradient.addColorStop("1.0","red");
  11. // Fill with gradient
  12. ctx.fillStyle=gradient;
  13. ctx.fillText("Big smile!",10,90);

strokeText()

Draws text on the canvas (no fill)

Definition and Usage

The strokeText() method draws text (with no fill) on the canvas. The default color of the text is black.

Tip: Use the font property to specify font and font size, and use the strokeStyle property to render the text in another color/gradient.














JavaScript syntax: context.strokeText(text,x,y,maxWidth);
Parameter Values

























Parameter Description
text Specifies the text that will be written on the canvas
x The x coordinate where to start painting the text (relative to the canvas)
y The y coordinate where to start painting the text (relative to the canvas)
maxWidth Optional. The maximum allowed width of the text, in pixels
Example
1 Write “Hello world!” and “Big smile!” (with gradient) on the canvas, using strokeText()

d36c6fedad0e327ab0c1bae21ebff2a4.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.font="20px Georgia";
  4. ctx.strokeText("Hello World!",10,50);
  5. ctx.font="30px Verdana";
  6. // Create gradient
  7. var gradient=ctx.createLinearGradient(0,0,c.width,0);
  8. gradient.addColorStop("0","magenta");
  9. gradient.addColorStop("0.5","blue");
  10. gradient.addColorStop("1.0","red");
  11. // Fill with gradient
  12. ctx.strokeStyle=gradient;
  13. ctx.strokeText("Big smile!",10,90);

measureText()

Returns an object that contains the width of the specified text

Definition and Usage

The measureText() method returns an object that contains the width of the specified text, in pixels.

Tip: Use this method if you need to know the width of a text, before writing it on the canvas.














JavaScript syntax: context.measureText(text).width;
Parameter Values













Parameter Description
text The text to be measured
Example
1 Check the width of the text, before writing it on the canvas

0b610adedec5644948cdaca7d42c8936.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. ctx.font="30px Arial";
  4. var txt="Hello World"
  5. ctx.fillText("width:" + ctx.measureText(txt).width,10,50)
  6. ctx.fillText(txt,10,100);

Image Drawing














Method Description
drawImage() Draws an image, canvas, or video onto the canvas

Method

drawImage()

Draws an image, canvas, or video onto the canvas

Definition and Usage

The drawImage() method draws an image, canvas, or video onto the canvas.

The drawImage() method can also draw parts of an image, and/or increase/reduce the image size.

Note: You cannot call the drawImage() method before the image has loaded. To ensure that the image has been loaded, you can call drawImage() from window.onload() or from document.getElementById(“imageID”).onload.

JavaScript Syntax

Position the image on the canvas:














JavaScript syntax: context.drawImage(img,x,y);

Position the image on the canvas, and specify width and height of the image:














JavaScript syntax: context.drawImage(img,x,y,width,height);

Clip the image and position the clipped part on the canvas:














JavaScript syntax: context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);
Parameter Values













































Parameter Description
img Specifies the image, canvas, or video element to use
sx Optional. The x coordinate where to start clipping
sy Optional. The y coordinate where to start clipping
swidth Optional. The width of the clipped image
sheight Optional. The height of the clipped image
x The x coordinate where to place the image on the canvas
y The y coordinate where to place the image on the canvas
width Optional. The width of the image to use (stretch or reduce the image)
height Optional. The height of the image to use (stretch or reduce the image)
Example
1 Draw the image onto the canvas

8fc4f97b9ec1f89be0938b8c24752e1b.png

  1. window.onload = function() {
  2. var c=document.getElementById("myCanvas");
  3. var ctx=c.getContext("2d");
  4. var img=document.getElementById("scream");
  5. ctx.drawImage(img,10,10);
  6. };
2 Position the image on the canvas, and specify width and height of the image

a0c162521f87ca304bb6280ab9cd5a02.png

  1. window.onload = function() {
  2. var c=document.getElementById("myCanvas");
  3. var ctx=c.getContext("2d");
  4. var img=document.getElementById("scream");
  5. ctx.drawImage(img,10,10,150,180);
  6. };
3 Clip the image and position the clipped part on the canvas

4d061212ba0e6996a936b9cb10b7bce8.png

  1. window.onload = function() {
  2. var c=document.getElementById("myCanvas");
  3. var ctx=c.getContext("2d");
  4. var img=document.getElementById("scream");
  5. ctx.drawImage(img,90,130,50,60,10,10,50,60);
  6. };
4 draws the current frame of the video every 20 millisecond

b0b3a591c96aef02405d5b05723fe150.png

  1. var v=document.getElementById("video1");
  2. var c=document.getElementById("myCanvas");
  3. var ctx=c.getContext('2d');
  4. var i;
  5. v.addEventListener('play',function() { i=window.setInterval(function() { ctx.drawImage(v,5,5,260,125)},20);},false);
  6. v.addEventListener('pause',function() { window.clearInterval(i);},false);
  7. v.addEventListener('ended',function() { clearInterval(i);},false);

Pixel Manipulation






















Property Description
width Returns the width of an ImageData object
height Returns the height of an ImageData object
data Returns an object that contains image data of a specified ImageData object





















Method Description
createImageData() Creates a new, blank ImageData object
getImageData() Returns an ImageData object that copies the pixel data for the specified rectangle on a canvas
putImageData() Puts the image data (from a specified ImageData object) back onto the canvas

Property

width

Returns the width of an ImageData object

Definition and Usage

The width property returns the width of an ImageData object, in pixels.

Tip: Look at createImageData(), getImageData(), and putImageData() to learn more about the ImageData object.

JavaScript Syntax













JavaScript syntax: imgData.width;
Example

height

Returns the height of an ImageData object

Definition and Usage

The height property returns the height of an ImageData object, in pixels.

Tip: Look at createImageData(), getImageData(), and putImageData() to learn more about the ImageData object.

JavaScript Syntax













JavaScript syntax: imgData.height;
Example

data

Returns an object that contains image data of a specified ImageData object

Definition and Usage

The data property returns an object that contains image data of the specified ImageData object.

For every pixel in an ImageData object there are four pieces of information, the RGBA values:

  • R - The color red (from 0-255)
  • G - The color green (from 0-255)
  • B - The color blue (from 0-255)
  • A - The alpha channel (from 0-255; 0 is transparent and 255 is fully visible)

The color/alpha information is held in an array, and is stored in the data property of the ImageData object.

Examples:

The syntax for making the first pixel in the ImageData object red:

  1. imgData=ctx.createImageData(100,100);
  2. imgData.data[0]=255;
  3. imgData.data[1]=0;
  4. imgData.data[2]=0;
  5. imgData.data[3]=255;

The syntax for making the second pixel in the ImageData object green:

  1. imgData=ctx.createImageData(100,100);
  2. imgData.data[4]=0;
  3. imgData.data[5]=255;
  4. imgData.data[6]=0;
  5. imgData.data[7]=255;

Tip: Look at createImageData(), getImageData(), and putImageData() to learn more about the ImageData object.

JavaScript Syntax













JavaScript syntax: imageData.data;
Example

Method

createImageData()

Creates a new, blank ImageData object

Definition and Usage

The createImageData() method creates a new, blank ImageData object. The new object’s pixel values are transparent black by default.

For every pixel in an ImageData object there are four pieces of information, the RGBA values:

  • R - The color red (from 0-255)
  • G - The color green (from 0-255)
  • B - The color blue (from 0-255)
  • A - The alpha channel (from 0-255; 0 is transparent and 255 is fully visible)

So, transparent black indicates: (0,0,0,0).

The color/alpha information is held in an array, and since the array contains 4 pieces of information for every pixel, the array’s size is 4 times the size of the ImageData object: widthheight4. (An easier way to find the size of the array, is to use ImageDataObject.data.length)

The array containing the color/alpha information is stored in the data property of the ImageData object.

Tip: After you have manipulated the color/alpha information in the array, you can copy the image data back onto the canvas with the putImageData() method.

Examples:

The syntax for making the first pixel in the ImageData object red:

  1. imgData=ctx.createImageData(100,100);
  2. imgData.data[0]=255;
  3. imgData.data[1]=0;
  4. imgData.data[2]=0;
  5. imgData.data[3]=255;

The syntax for making the second pixel in the ImageData object green:

  1. imgData=ctx.createImageData(100,100);
  2. imgData.data[4]=0;
  3. imgData.data[5]=255;
  4. imgData.data[6]=0;
  5. imgData.data[7]=255;
JavaScript Syntax

There are two versions of the createImageData() method:

1.This creates a new ImageData object with the specified dimensions (in pixels):














JavaScript syntax: var imgData=context.createImageData(width,height);

2.This creates a new ImageData object with the same dimensions as the object specified by anotherImageData (this does not copy the image data):














JavaScript syntax: var imgData=context.createImageData(imageData);
Parameter Values





















Parameter Description
width The width of the new ImageData object, in pixels
height The height of the new ImageData object, in pixels
imageData anotherImageData object
Example
1 Create a 100*100 pixels ImageData object, and put it onto the canvas:

6cb5c94ab8e8d33668bb9a26b6d788c8.png

  1. var c = document.getElementById("myCanvas");
  2. var ctx = c.getContext("2d");
  3. var imgData = ctx.createImageData(100, 100);
  4. var i;
  5. for (i = 0; i < imgData.data.length / 2; i += 4) {
  6. imgData.data[i+0] = 255;
  7. imgData.data[i+1] = 0;
  8. imgData.data[i+2] = 0;
  9. imgData.data[i+3] = 255;
  10. }
  11. for (i = imgData.data.length / 2; i < imgData.data.length; i += 4) {
  12. imgData.data[i+0] = 0;
  13. imgData.data[i+1] = 255;
  14. imgData.data[i+2] = 0;
  15. imgData.data[i+3] = 255;
  16. }
  17. ctx.putImageData(imgData, 10, 10);

getImageData()

Returns an ImageData object that copies the pixel data for the specified rectangle on a canvas

Definition and Usage

The getImageData() method returns an ImageData object that copies the pixel data for the specified rectangle on a canvas.

Note: The ImageData object is not a picture, it specifies a part (rectangle) on the canvas, and holds information of every pixel inside that rectangle.

For every pixel in an ImageData object there are four pieces of information, the RGBA values:

  • R - The color red (from 0-255)
  • G - The color green (from 0-255)
  • B - The color blue (from 0-255)
  • A - The alpha channel (from 0-255; 0 is transparent and 255 is fully visible)

The color/alpha information is held in an array, and is stored in the data property of the ImageData object.

Tip: After you have manipulated the color/alpha information in the array, you can copy the image data back onto the canvas with the putImageData() method.

Example:

The code for getting color/alpha information of the first pixel in the returned ImageData object:

  1. red=imgData.data[0];
  2. green=imgData.data[1];
  3. blue=imgData.data[2];
  4. alpha=imgData.data[3];

Tip: You can also use the getImageData() method to invert the color of every pixels of an image on the canvas.

Loop through all the pixels and change the color values using this formula:

  1. red=255-old_red;
  2. green=255-old_green;
  3. blue=255-old_blue;

See below for a try it yourself example!


JavaScript Syntax













JavaScript syntax: context.getImageData(x,y,width,height);
Parameter Values

























Parameter Description
x The x coordinate (in pixels) of the upper-left corner to start copy from
y The y coordinate (in pixels) of the upper-left corner to start copy from
width The width of the rectangular area you will copy
height The height of the rectangular area you will copy
Example
1 Use getImageData() to invert the color of every pixels of an image on the canvas

c0f144f736fc2c25a32333ae4e58d406.png

a683e2d7f982446def6f567841067f21.png

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. var img=document.getElementById("scream");
  4. ctx.drawImage(img,0,0);
  5. var imgData=ctx.getImageData(0,0,c.width,c.height);
  6. // invert colors
  7. for (var i=0;i<imgData.data.length;i+=4)
  8. {
  9. imgData.data[i]=255-imgData.data[i];
  10. imgData.data[i+1]=255-imgData.data[i+1];
  11. imgData.data[i+2]=255-imgData.data[i+2];
  12. imgData.data[i+3]=255;
  13. }
  14. ctx.putImageData(imgData,0,0);

putImageData()

Puts the image data (from a specified ImageData object) back onto the canvas

Definition and Usage

The putImageData() method puts the image data (from a specified ImageData object) back onto the canvas.

Tip: Read about the getImageData() method that copies the pixel data for a specified rectangle on a canvas.

Tip: Read about the createImageData() method that creates a new, blank ImageData object.

JavaScript Syntax













JavaScript syntax: context.putImageData(imgData,x,y,dirtyX,dirtyY,dirtyWidth,dirtyHeight);
Parameter Values





































Parameter Description
imgData Specifies the ImageData object to put back onto the canvas
x The x-coordinate, in pixels, of the upper-left corner of the ImageData object
y The y-coordinate, in pixels, of the upper-left corner of the ImageData object
dirtyX Optional. The horizontal (x) value, in pixels, where to place the image on the canvas
dirtyY Optional. The vertical (y) value, in pixels, where to place the image on the canvas
dirtyWidth Optional. The width to use to draw the image on the canvas
dirtyHeight Optional. The height to use to draw the image on the canvas
Example
1 putImageData() with optional parameter

8fe22960aeb25c921907ee5d9d394a67.png

  1. <img id="scream" src="img_the_scream.jpg" alt="The Scream" width="220" height="277">
  2. <canvas id="myCanvas" width="220" height="277" style="border:1px solid #d3d3d3;">
  3. Your browser does not support the HTML5 canvas tag.</canvas>
  4. <script> document.getElementById("scream").onload = function() { var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); var img = document.getElementById("scream"); ctx.drawImage(img, 0, 0); var imgData = ctx.getImageData(0, 0, c.width, c.height); // invert colors var i; for (i = 0; i < imgData.data.length; i += 4) { imgData.data[i] = 255 - imgData.data[i]; imgData.data[i+1] = 255 - imgData.data[i+1]; imgData.data[i+2] = 255 - imgData.data[i+2]; imgData.data[i+3] = 255; } ctx.putImageData(imgData, 0, 0, 0, 0, 110, 277); }; </script>

Compositing


















Property Description
globalAlpha Sets or returns the current alpha or transparency value of the drawing
globalCompositeOperation Sets or returns how a new image are drawn onto an existing image

Property

globalAlpha

Sets or returns the current alpha or transparency value of the drawing

Definition and Usage

The globalAlpha property sets or returns the current alpha or transparency value of the drawing.

The globalAlpha property value must be a number between 0.0 (fully transparent) and 1.0 (no transparancy).


















Default value: 1.0
JavaScript syntax: context.globalAlpha=number;
Property Values













Value Description
number The transparency value. Must be a number between 0.0 (fully transparent) and 1.0 (no transparancy)
Example
1 First, draw a red rectangle, then set transparency (globalAlpha) to 0.5, and then draw a blue and a green rectangle

e9895e312f4f74de2b92b5e90dc9c2e4.png

  1. var c = document.getElementById("myCanvas");
  2. var ctx = c.getContext("2d");
  3. ctx.fillStyle = "red";
  4. ctx.fillRect(20, 20, 75, 50);
  5. //Turn transparency on
  6. ctx.globalAlpha = 0.1;
  7. ctx.fillStyle = "blue";
  8. ctx.fillRect(50, 50, 75, 50);
  9. ctx.fillStyle = "green";
  10. ctx.fillRect(80, 80, 75, 50);

globalCompositeOperation

Sets or returns how a new image are drawn onto an existing image

Definition and Usage

The globalCompositeOperation property sets or returns how a source (new) image are drawn onto a destination (existing) image.

source image = drawings you are about to place onto the canvas.

destination image = drawings that are already placed onto the canvas.


















Default value: source-over
JavaScript syntax: context.globalCompositeOperation=“source-in”;
Property Values





















































Value Description
source-over Default. Displays the source image over the destination image
source-atop Displays the source image on top of the destination image. The part of the source image that is outside the destination image is not shown
source-in Displays the source image in to the destination image. Only the part of the source image that is INSIDE the destination image is shown, and the destination image is transparent
source-out Displays the source image out of the destination image. Only the part of the source image that is OUTSIDE the destination image is shown, and the destination image is transparent
destination-over Displays the destination image over the source image
destination-atop Displays the destination image on top of the source image. The part of the destination image that is outside the source image is not shown
destination-in Displays the destination image in to the source image. Only the part of the destination image that is INSIDE the source image is shown, and the source image is transparent
destination-out Displays the destination image out of the source image. Only the part of the destination image that is OUTSIDE the source image is shown, and the source image is transparent
lighter Displays the source image + the destination image
copy Displays the source image. The destination image is ignored
xor The source image is combined by using an exclusive OR with the destination image
Example
1 All the globalCompositeOperation property values

e0f84b3382050498a5904045e731e9ea.png

  1. var gco = new Array();
  2. gco.push("source-atop");
  3. gco.push("source-in");
  4. gco.push("source-out");
  5. gco.push("source-over");
  6. gco.push("destination-atop");
  7. gco.push("destination-in");
  8. gco.push("destination-out");
  9. gco.push("destination-over");
  10. gco.push("lighter");
  11. gco.push("copy");
  12. gco.push("xor");
  13. var n;
  14. for (n = 0; n < gco.length; n++) {
  15. document.write("<div id='p_" + n + "' style='float:left;'>" + gco[n] + ":<br>");
  16. var c = document.createElement("canvas");
  17. c.width = 120;
  18. c.height = 100;
  19. document.getElementById("p_" + n).appendChild(c);
  20. var ctx = c.getContext("2d");
  21. ctx.fillStyle = "blue";
  22. ctx.fillRect(10, 10, 50, 50);
  23. ctx.globalCompositeOperation = gco[n];
  24. ctx.beginPath();
  25. ctx.fillStyle = "red";
  26. ctx.arc(50, 50, 30, 0, 2 * Math.PI);
  27. ctx.fill();
  28. document.write("</div>");
  29. }

Other


























Method Description
save() Saves the state of the current context (Push the current state on the state stack)
restore() Returns previously saved path state and attributes (Remove the top state from the state stack and thus restore the previous state that was pushed on the state stack)
getContext() Returns the so-called context, i.e. an object that exposes an API for drawing on the canvas.
toDataURL() Returns a ‘data:’ URL for the image in the canvas

Method

save()

Definition and Usage

Push the current state on the state stack.

A drawing state is the set of the current settings of a CanvasRenderingContext2D object. It includes:

  • the current style values (strokeStyle and fillStyle),
  • globalAlpha and globalCompositeOperation,
  • the line (lineWidth, lineCap, lineJoin, miterLimit),
  • shadow (shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor)
  • text settings (font, textAlign, textBaseline),
  • the current clipping region
  • the current transformation matrix.

Each CanvasRenderingContext2D object maintains a stack of drawing states. And with save() and restore(), drawing states can be pushed onto this stack and recovered at a later point.

Note, that the drawing state does not include the current path or bitmaps. So save() and restore() do not save and restore entire canvas pictures, i.e. entire contents of the given context. For that, you should use ImageData objects and the getImageData() and putImageData() methods (see the chapter on pixel manipulation).

Example
1 save() and restore()

Suppose we draw 5 figures, each one a fillRect() rectangle with two lines of strokeText() text in it, like so:

bd70e5568fe740342e8558b24cb4684c.png

As it is apparent from the picture, we use 3 different style settings for the 5 figures, defined as states:

  • State A with a linear gradient fillStyle, running from top red to bottom green and yellow strokeStyle.
  • State B with a radial gradient fillStyle, running from a orange center start to an outer green end circle and green strokeStyle.
  • State C with dark gray fillStyle and light gray strokeStyle.

We could generate the previous canvas by following these steps:

  1. declare State A and draw Figure 1 and 5
  2. declare State B and draw Figure 2 and 4
  3. declare State C and draw Figure 3

But since we want to demonstrate the use of save() and restore(), we create the Figures in their presented order:

  1. set State A, draw Figure 1 and save State A on the state stack
  2. set State B, draw Figure 2 and save State B on the state stack
  3. set State C and draw Figure 3
  4. overwrite State C by restoring State B from the stack and draw Figure 4
  5. restore State A and draw Figure 5

The full source code that actually generated the canvas is this:

  1. // Text style settings (these will be part of Start A, B, and C alike, because they do not change)
  2. context.textAlign = 'center';
  3. context.textBaseline = 'middle';
  4. context.lineWidth = 2.0;
  5. context.font = '25px Arial';
  6. // Settings for State A
  7. var verticalGrad = context.createLinearGradient (0,0,0,200);
  8. verticalGrad.addColorStop (0,'red');
  9. verticalGrad.addColorStop (1,'green');
  10. context.fillStyle = verticalGrad;
  11. context.strokeStyle = 'yellow';
  12. // Draw Figure 1
  13. context.fillRect (25,25,100,150);
  14. context.strokeText ("Fig 1",75,50);
  15. context.strokeText ("State A", 75,125);
  16. // Save State A
  17. context.save();
  18. // Settings for State B
  19. var radGrad = context.createRadialGradient (375,100,5, 375,100,200);
  20. radGrad.addColorStop (0,'orange');
  21. radGrad.addColorStop (1,'yellow');
  22. context.fillStyle = radGrad;
  23. context.strokeStyle = 'green';
  24. // Draw Figure 2
  25. context.fillRect (175,25,100,150);
  26. context.strokeText ("Fig 2",225,50);
  27. context.strokeText ("State B",225,125);
  28. // Save State B
  29. context.save();
  30. // Settings for State C
  31. context.fillStyle = '#888888';
  32. context.strokeStyle = '#EEEEEE';
  33. // Draw Figure 3
  34. context.fillRect (325,25,100,150);
  35. context.strokeText ("Fig 3",375,50);
  36. context.strokeText ("State C",375,125);
  37. // Pop State C and restore State B
  38. context.restore();
  39. // Draw Figure 4
  40. context.fillRect (475,25,100,150);
  41. context.strokeText ("Fig 4",525,50);
  42. context.strokeText ("State B",525,125);
  43. // Pop state B and restore state A
  44. context.restore();
  45. // Draw Figure 5
  46. context.fillRect (625,25,100,150);
  47. context.strokeText ("Fig 5",675,50);
  48. context.strokeText ("State A",675,125);

restore()

Remove the top state from the state stack and thus restore the previous state that was pushed on the state stack.

Example

参考上文save()的Example

getContext()

HTMLCanvasElement.getContext (contextId)

returns the so-called context, i.e. an object that exposes an API for drawing on the canvas. Currently, only the CanvasRenderingContext2D object is supported, and for that the contextId is ‘2d’. The result of this call will be null if the given context ID is not supported.

This context, which will always be the 2D context in the sequel, is attached to the canvas and accessible by a call of canvas.getContext(‘2d’). This context is where all the action takes place. It provides the interface for all the drawings added to the given canvas and explaining the CanvasRenderingContext2D object below is thus the biggest part of this manual.

The [W3C] document announces that there will probably be a ‘3d’ context in the future, based on the OpenGL ES API.

Example

toDataURL()

Returns a data: URL for the image in the canvas. The first optional type argument controls the type of the image to be returned (e.g. PNG or JPEG). The default type is ‘image/png’ for PNG images. The other arguments are specific to the type and control the way that the image is generated.

Example
1 Convert the canvas into a data URL

Let us consider a very tiny canvas example, say a red 20x20 pixel rectangle

7fcbeeaffe08597e3db11e0e9597608b.png

generated by the following code

  1. <canvas id="DataUrlSample" width=20 height=20></canvas>
  2. <script> var canvas = document.getElementById ('DataUrlSample'); var context = canvas.getContext ('2d'); context.fillStyle = 'red'; context.fillRect (0, 0, 20, 20); </script>

We can now convert the canvas into a PNG data URL by calling:

  1. var dataUrl = canvas.toDataURL();

and dataUrl now holds this string:

  1. data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAK0lEQVQ4T2P8z8Dwn4GKgHHUQIpDczQMKQ5ChtEwHA1DMkJgNNmQEWhoWgBMAiftPRtHngAAAABJRU5ErkJggg==

If you copy this string and put it into the address field of your browser, you should see the picture of the red square.

We can also convert to a JPEG like so

  1. var dataUrl = canvas.toDataURL('image/jpeg');

and then the result is this string:

  1. data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBD/wAARCAAUABQDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAj/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFgEBAQEAAAAAAAAAAAAAAAAAAAcJ/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AnQBDGqYAAAAAD//Z

You can copy all this and call it in your browser to get the little red square, again.

For a more convenient solution, we can attach these lines to the previous code:

  1. canvas.onclick = function () {
  2. window.location = canvas.toDataURL('image/png');
  3. };

If we then click on the canvas, the browser opens the data URL into the address field and thus shows the image. And then, the user can choose to save this image as a PNG file.

发表评论

表情:
评论列表 (有 0 条评论,279人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Canvas学习笔记——马赛克案例

    这篇文章要讲的是如何将一张照片变成马赛克的照片,利用`Canvas`中操作像素的方法可实现。马赛克的原理无非就是视觉上把原来的像素大小放大,将若干个小像素组成一个块变成大像素,