1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
|
---
title: Using images
slug: Web/API/Canvas_API/Tutorial/Using_images
translation_of: Web/API/Canvas_API/Tutorial/Using_images
original_slug: Web/Guide/HTML/Canvas_tutorial/Using_images
---
<div>{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Drawing_text", "Web/API/Canvas_API/Tutorial/Transformations" )}}</div>
<div class="summary">
<p>Até agora nós criamos nossos próprios <a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes">shapes</a> e aplicamos estilos(<a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors">applied styles</a>) a eles. Um dos recursos mais interessantes do {{HTMLElement("canvas")}} é a capacidade de usar imagens. Eles podem ser usados para composição dinâmica de fotos ou como pano de fundo de gráficos, como sprites em jogos e assim por diante. Imagens externas podem ser usadas em qualquer formato suportado pelo navegador, tais como PNG, GIF, ou JPEG. Você pode até usar a imagem produzida por outros elementos da tela na mesma página que a fonte!</p>
</div>
<p>A importação de imagens para o canvas é basicamente um processo de duas etapas:</p>
<ol>
<li>Obter uma referência a um objeto {{domxref("HTMLImageElement")}} ou a outro elemento do canvas como fonte. Também é possível usar imagens fornecendo uma URL.</li>
<li>Desenhar a imagem no canvas usando a função <code>drawImage()</code> .</li>
</ol>
<p>Vamos dar uma olhada em como fazer isso.</p>
<h2 id="Getting_images_to_draw">Getting images to draw</h2>
<p>The canvas API is able to use any of the following data types as an image source:</p>
<dl>
<dt>{{domxref("HTMLImageElement")}}</dt>
<dd>These are images created using the <code>Image()</code> constructor, as well as any {{HTMLElement("img")}} element.</dd>
<dt>{{domxref("SVGImageElement")}}</dt>
<dd>These are images embedded using the {{SVGElement("image")}} element.</dd>
<dt>{{domxref("HTMLVideoElement")}}</dt>
<dd>Using an HTML {{HTMLElement("video")}} element as your image source grabs the current frame from the video and uses it as an image.</dd>
<dt>{{domxref("HTMLCanvasElement")}}</dt>
<dd>You can use another {{HTMLElement("canvas")}} element as your image source.</dd>
</dl>
<p>These sources are collectively referred to by the type {{domxref("CanvasImageSource")}}.</p>
<p>There are several ways to get images for use on a canvas.</p>
<h3 id="Using_images_from_the_same_page">Using images from the same page</h3>
<p>We can obtain a reference to images on the same page as the canvas by using one of:</p>
<ul>
<li>The {{domxref("document.images")}} collection</li>
<li>The {{domxref("document.getElementsByTagName()")}} method</li>
<li>If you know the ID of the specific image you wish to use, you can use {{domxref("document.getElementById()")}} to retrieve that specific image</li>
</ul>
<h3 id="Using_images_from_other_domains">Using images from other domains</h3>
<p>Using the {{htmlattrxref("crossorigin", "img")}} attribute of an {{HTMLElement("img")}} element (reflected by the {{domxref("HTMLImageElement.crossOrigin")}} property), you can request permission to load an image from another domain for use in your call to <code>drawImage()</code>. If the hosting domain permits cross-domain access to the image, the image can be used in your canvas without tainting it; otherwise using the image will <a href="https://developer.mozilla.org/en-US/docs/HTML/CORS_Enabled_Image#What_is_a_.22tainted.22_canvas.3F" rel="internal">taint the canvas</a>.</p>
<h3 id="Using_other_canvas_elements">Using other canvas elements</h3>
<p>Just as with normal images, we access other canvas elements using either the {{domxref("document.getElementsByTagName()")}} or {{domxref("document.getElementById()")}} method. Be sure you've drawn something to the source canvas before using it in your target canvas.</p>
<p>One of the more practical uses of this would be to use a second canvas element as a thumbnail view of the other larger canvas.</p>
<h3 id="Creating_an_image_from_scratch">Creating an image from scratch</h3>
<p>Another option is to create new {{domxref("HTMLImageElement")}} objects in our script. To do this, you can use the convenient <code>Image()</code> constructor:</p>
<pre class="brush: js">var img = new Image(); // Create new img element
img.src = 'myImage.png'; // Set source path
</pre>
<p>When this script gets executed, the image starts loading.</p>
<p>If you try to call <code>drawImage()</code> before the image has finished loading, it won't do anything (or, in older browsers, may even throw an exception). So you need to be sure to use the load event so you don't try this before the image has loaded:</p>
<pre class="brush: js">var img = new Image(); // Create new img element
img.addEventListener('load', function() {
// execute drawImage statements here
}, false);
img.src = 'myImage.png'; // Set source path
</pre>
<p>If you're only using one external image this can be a good approach, but once you need to track more than one we need to resort to something more clever. It's beyond the scope of this tutorial to look at image pre-loading tactics, but you should keep that in mind.</p>
<h3 id="Embedding_an_image_via_data_URL">Embedding an image via data: URL</h3>
<p>Another possible way to include images is via the <a class="external" href="/en-US/docs/Web/HTTP/data_URIs" rel="external" title="http://en.wikipedia.org/wiki/Data:_URL">data: url</a>. Data URLs allow you to completely define an image as a Base64 encoded string of characters directly in your code.</p>
<pre class="brush: js">var img = new Image(); // Create new img element
img.src = 'data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==';
</pre>
<p>One advantage of data URLs is that the resulting image is available immediately without another round trip to the server. Another potential advantage is that it is also possible to encapsulate in one file all of your <a href="/en-US/docs/Web/CSS" title="/en-US/docs/Web/CSS">CSS</a>, <a href="/en-US/docs/Web/JavaScript" title="/en-US/docs/Web/JavaScript">JavaScript</a>, <a href="/en-US/docs/Web/HTML" title="/en-US/docs/Web/HTML">HTML</a>, and images, making it more portable to other locations.</p>
<p>Some disadvantages of this method are that your image is not cached, and for larger images the encoded url can become quite long.</p>
<h3 id="Using_frames_from_a_video">Using frames from a video</h3>
<p>You can also use frames from a video being presented by a {{HTMLElement("video")}} element (even if the video is not visible). For example, if you have a {{HTMLElement("video")}} element with the ID "myvideo", you can do this:</p>
<pre class="brush: js">function getMyVideo() {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
return document.getElementById('myvideo');
}
}
</pre>
<p>This returns the {{domxref("HTMLVideoElement")}} object for the video, which, as covered earlier, is one of the objects that can be used as a <code>CanvasImageSource</code>.</p>
<h2 id="Drawing_images">Drawing images</h2>
<p>Once we have a reference to our source image object we can use the <code>drawImage()</code> method to render it to the canvas. As we will see later the <code>drawImage()</code> method is overloaded and has several variants. In its most basic form it looks like this:</p>
<dl>
<dt>{{domxref("CanvasRenderingContext2D.drawImage", "drawImage(image, x, y)")}}</dt>
<dd>Draws the <code>CanvasImageSource</code> specified by the <code>image</code> parameter at the coordinates (<code>x</code>, <code>y</code>).</dd>
</dl>
<div class="note">
<p>SVG images must specify a width and height in the root <svg> element.</p>
</div>
<h3 id="Example_A_simple_line_graph">Example: A simple line graph</h3>
<p>In the following example, we will use an external image as the backdrop for a small line graph. Using backdrops can make your script considerably smaller because we can avoid the need for code to generate the background. In this example, we're only using one image, so I use the image object's <code>load</code> event handler to execute the drawing statements. The <code>drawImage()</code> method places the backdrop at the coordinate (0, 0), which is the top-left corner of the canvas.</p>
<div class="hidden">
<pre class="brush: html"><html>
<body onload="draw();">
<canvas id="canvas" width="180" height="150"></canvas>
</body>
</html>
</pre>
</div>
<pre class="brush: js;highlight[5]">function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
ctx.beginPath();
ctx.moveTo(30, 96);
ctx.lineTo(70, 66);
ctx.lineTo(103, 76);
ctx.lineTo(170, 15);
ctx.stroke();
};
img.src = 'https://mdn.mozillademos.org/files/5395/backdrop.png';
}</pre>
<p>The resulting graph looks like this:</p>
<p>{{EmbedLiveSample("Example_A_simple_line_graph", 220, 160, "https://mdn.mozillademos.org/files/206/Canvas_backdrop.png")}}</p>
<h2 id="Scaling">Scaling</h2>
<p>The second variant of the <code>drawImage()</code> method adds two new parameters and lets us place scaled images on the canvas.</p>
<dl>
<dt>{{domxref("CanvasRenderingContext2D.drawImage", "drawImage(image, x, y, width, height)")}}</dt>
<dd>This adds the <code>width</code> and <code>height</code> parameters, which indicate the size to which to scale the image when drawing it onto the canvas.</dd>
</dl>
<h3 id="Example_Tiling_an_image">Example: Tiling an image</h3>
<p>In this example, we'll use an image as a wallpaper and repeat it several times on the canvas. This is done simply by looping and placing the scaled images at different positions. In the code below, the first <code>for</code> loop iterates over the rows. The second <code>for</code> loop iterates over the columns. The image is scaled to one third of its original size, which is 50x38 pixels.</p>
<div class="note">
<p><strong>Note</strong>: Images can become blurry when scaling up or grainy if they're scaled down too much. Scaling is probably best not done if you've got some text in it which needs to remain legible.</p>
</div>
<div class="hidden">
<pre class="brush: html"><html>
<body onload="draw();">
<canvas id="canvas" width="150" height="150"></canvas>
</body>
</html>
</pre>
</div>
<pre class="brush: js">function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.onload = function() {
for (var i = 0; i < 4; i++) {
for (var j = 0; j < 3; j++) {
ctx.drawImage(img, j * 50, i * 38, 50, 38);
}
}
};
img.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg';
}</pre>
<p>The resulting canvas looks like this:</p>
<p>{{EmbedLiveSample("Example_Tiling_an_image", 160, 160, "https://mdn.mozillademos.org/files/251/Canvas_scale_image.png")}}</p>
<h2 id="Slicing">Slicing</h2>
<p>The third and last variant of the <code>drawImage()</code> method has eight parameters in addition to the image source. It lets us cut out a section of the source image, then scale and draw it on our canvas.</p>
<dl>
<dt>{{domxref("CanvasRenderingContext2D.drawImage", "drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)")}}</dt>
<dd>Given an <code>image</code>, this function takes the area of the source image specified by the rectangle whose top-left corner is (<code>sx</code>, <code>sy</code>) and whose width and height are <code>sWidth</code> and <code>sHeight</code> and draws it into the canvas, placing it on the canvas at (<code>dx</code>, <code>dy</code>) and scaling it to the size specified by <code>dWidth</code> and <code>dHeight</code>.</dd>
</dl>
<p><img alt="" class="internal" src="https://mdn.mozillademos.org/files/225/Canvas_drawimage.jpg" style="float: right; height: 290px; width: 300px;">To really understand what this does, it may help to look at the image to the right. The first four parameters define the location and size of the slice on the source image. The last four parameters define the rectangle into which to draw the image on the destination canvas.</p>
<p>Slicing can be a useful tool when you want to make compositions. You could have all elements in a single image file and use this method to composite a complete drawing. For instance, if you want to make a chart you could have a PNG image containing all the necessary text in a single file and depending on your data could change the scale of your chart fairly easily. Another advantage is that you don't need to load every image individually, which can improve load performance.</p>
<h3 id="Example_Framing_an_image">Example: Framing an image</h3>
<p>In this example, we'll use the same rhino as in the previous example, but we'll slice out its head and composite it into a picture frame. The picture frame image is a 24-bit PNG which includes a drop shadow. Because 24-bit PNG images include a full 8-bit alpha channel, unlike GIF and 8-bit PNG images, it can be placed onto any background without worrying about a matte color.</p>
<pre class="brush: html"><html>
<body onload="draw();">
<canvas id="canvas" width="150" height="150"></canvas>
<div style="display:none;">
<img id="source" src="https://mdn.mozillademos.org/files/5397/rhino.jpg" width="300" height="227">
<img id="frame" src="https://mdn.mozillademos.org/files/242/Canvas_picture_frame.png" width="132" height="150">
</div>
</body>
</html>
</pre>
<pre class="brush: js">function draw() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// Draw slice
ctx.drawImage(document.getElementById('source'),
33, 71, 104, 124, 21, 20, 87, 104);
// Draw frame
ctx.drawImage(document.getElementById('frame'), 0, 0);
}</pre>
<p>We took a different approach to loading the images this time. Instead of loading them by creating new {{domxref("HTMLImageElement")}} objects, we included them as {{HTMLElement("img")}} tags directly in our HTML source and retrieved the images from those. The images are hidden from output by setting the CSS property {{cssxref("display")}} to none for those images.</p>
<p>{{EmbedLiveSample("Example_Framing_an_image", 160, 160, "https://mdn.mozillademos.org/files/226/Canvas_drawimage2.jpg")}}</p>
<p>The script itself is very simple. Each {{HTMLElement("img")}} is assigned an ID attribute, which makes them easy to select using {{domxref("document.getElementById()")}}. We then simply use <code>drawImage()</code> to slice the rhino out of the first image and scale him onto the canvas, then draw the frame on top using a second <code>drawImage()</code> call.</p>
<h2 id="Art_gallery_example">Art gallery example</h2>
<p>In the final example of this chapter, we'll build a little art gallery. The gallery consists of a table containing several images. When the page is loaded, a {{HTMLElement("canvas")}} element is inserted for each image and a frame is drawn around it.</p>
<p>In this case, every image has a fixed width and height, as does the frame that's drawn around them. You could enhance the script so that it uses the image's width and height to make the frame fit perfectly around it.</p>
<p>The code below should be self-explanatory. We loop through the {{domxref("document.images")}} container and add new canvas elements accordingly. Probably the only thing to note, for those not so familiar with the DOM, is the use of the {{domxref("Node.insertBefore")}} method. <code>insertBefore()</code> is a method of the parent node (a table cell) of the element (the image) before which we want to insert our new node (the canvas element).</p>
<pre class="brush: html"><html>
<body onload="draw();">
<table>
<tr>
<td><img src="https://mdn.mozillademos.org/files/5399/gallery_1.jpg"></td>
<td><img src="https://mdn.mozillademos.org/files/5401/gallery_2.jpg"></td>
<td><img src="https://mdn.mozillademos.org/files/5403/gallery_3.jpg"></td>
<td><img src="https://mdn.mozillademos.org/files/5405/gallery_4.jpg"></td>
</tr>
<tr>
<td><img src="https://mdn.mozillademos.org/files/5407/gallery_5.jpg"></td>
<td><img src="https://mdn.mozillademos.org/files/5409/gallery_6.jpg"></td>
<td><img src="https://mdn.mozillademos.org/files/5411/gallery_7.jpg"></td>
<td><img src="https://mdn.mozillademos.org/files/5413/gallery_8.jpg"></td>
</tr>
</table>
<img id="frame" src="https://mdn.mozillademos.org/files/242/Canvas_picture_frame.png" width="132" height="150">
</body>
</html>
</pre>
<p>And here's some CSS to make things look nice:</p>
<pre class="brush: css">body {
background: 0 -100px repeat-x url(https://mdn.mozillademos.org/files/5415/bg_gallery.png) #4F191A;
margin: 10px;
}
img {
display: none;
}
table {
margin: 0 auto;
}
td {
padding: 15px;
}
</pre>
<p>Tying it all together is the JavaScript to draw our framed images:</p>
<pre class="brush: js">function draw() {
// Loop through all images
for (var i = 0; i < document.images.length; i++) {
// Don't add a canvas for the frame image
if (document.images[i].getAttribute('id') != 'frame') {
// Create canvas element
canvas = document.createElement('canvas');
canvas.setAttribute('width', 132);
canvas.setAttribute('height', 150);
// Insert before the image
document.images[i].parentNode.insertBefore(canvas,document.images[i]);
ctx = canvas.getContext('2d');
// Draw image to canvas
ctx.drawImage(document.images[i], 15, 20);
// Add frame
ctx.drawImage(document.getElementById('frame'), 0, 0);
}
}
}</pre>
<p>{{EmbedLiveSample("Art_gallery_example", 725, 400)}}</p>
<h2 id="Controlling_image_scaling_behavior">Controlling image scaling behavior</h2>
<p>As mentioned previously, scaling images can result in fuzzy or blocky artifacts due to the scaling process. You can use the drawing context's {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled", "imageSmoothingEnabled")}} property to control the use of image smoothing algorithms when scaling images within your context. By default, this is <code>true</code>, meaning images will be smoothed when scaled. You can disable this feature like this:</p>
<pre class="brush: js">ctx.mozImageSmoothingEnabled = false;
ctx.webkitImageSmoothingEnabled = false;
ctx.msImageSmoothingEnabled = false;
ctx.imageSmoothingEnabled = false;
</pre>
<p>{{PreviousNext("Web/API/Canvas_API/Tutorial/Drawing_text", "Web/API/Canvas_API/Tutorial/Transformations")}}</p>
|