OSDN Git Service

Regular updates
[twpd/master.git] / canvas.md
1 ---
2 title: Canvas
3 category: JavaScript
4 layout: 2017/sheet
5 ---
6
7 ### Getting the context
8
9 ```js
10 var canvas = document.getElementById('c')
11 var c = canvas.getContext('2d')
12 ```
13
14 ### Basic drawing
15
16 ```js
17 // x = 10, y = 20, width = 200, height = 100
18 c.fillStyle = '#ff0000'
19 c.strokeStyle = '#ff00ff'
20 ```
21
22 ```js
23 c.lineWidth = 5
24 c.lineCap = 'round'
25 ```
26
27 ```js
28 c.fillRect(10, 20, 200, 100)
29 ```
30
31 ```js
32 c.stroke()
33 c.fill()
34 ```
35
36 ### Saving and restoring
37
38 ```js
39 c.save()
40 ```
41
42 ```js
43 c.restore()
44 ```
45
46 Saves: `strokeStyle` `fillStyle` `globalAlpha` `lineWidth` `lineCap` `lineJoin` `miterLimit` `shadowOffsetX` `shadowOffsetY` `shadowBlur` `shadowColor`
47 `globalCompositeOperation`, Transformations (`translate` `rotate` `scale` `transform` `setTransform`), Clipping path
48
49
50 ### Animation
51
52 ```js
53 onframe: function() {
54   c.clearRect(0, 0, w, h)
55 }
56 ```
57
58 ### Transformations
59
60 ```js
61 c.translate(0, 0)
62 c.rotate(Math.PI*2/5)
63 c.scale(1.0, 1.0)
64 ```
65
66 To rotate along origin:
67
68 ```js
69 c.translate(ox, oy)
70 c.rotate(theta)
71 c.translate(-ox, -oy)
72 ```
73
74 To scale along origin:
75
76 ```js
77 c.translate(-ox*x, -oy*y)
78 c.scale(x, y)
79 c.translate(ox/x, oy/y)
80 ```
81
82 See [MDN: Transformations][xform].
83
84 ### Image drawing
85
86 ```js
87 c.drawImage(image, dx, dy, [dw, dh]);
88 /* `image` can be HTML Image/Canvas/Video */
89 ```
90
91 See [MDN: Images][images].
92
93 ### Colors, styles shadows
94
95 ```js
96 c.strokeStyle = '#ff00ff';
97 c.fillStyle = '#ff00ff';
98 ```
99
100 ```js
101 c.shadowOffsetX = 0;
102 c.shadowOffsetY = 0;
103 c.shadowOffsetBlur = 3.0;
104 c.shadowColor = 'rgba(0,0,0,0.2)';
105 ```
106
107 See [MDN: Styles][styles]
108
109 ### Gradients
110
111 ```js
112 gr = c.createLinearGradient(x0,y0,x1,y1)
113 gr = c.createRadialGradient(x0,y0,r0,x1,y1,r1)
114 pat = c.createPattern(image, 'repeat-x')
115 ```
116
117 ```js
118 c.fillStyle = gr
119 ```
120
121 ### Drawing
122
123 ```js
124 c.beginPath()
125 c.moveTo(x,y)
126 c.lineTo(x,y)
127 c.quadraticCurveTo(cpx,cpy,x,y)
128 c.bezierCurveTo(cp1x,cp1y,cp2x,cp2y)
129 c.arcTo(...)
130 c.arc(...)
131 c.closePath()
132 ```
133
134 ### More resources
135
136   * [Canvas Cheatsheet PDF][pdf]
137
138 [pdf]: http://www.nihilogic.dk/labs/canvas_sheet/HTML5_Canvas_Cheat_Sheet.pdf
139 [xform]: https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations
140 [styles]: https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Applying_styles_and_colors
141 [images]: https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Using_images