aboutsummaryrefslogtreecommitdiff
path: root/files/de/web/guide/html/canvas_tutorial/bilder/index.html
blob: b636807f971225ed3240cc2472be5cd33beb7363 (plain)
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
---
title: Bilder
slug: Web/Guide/HTML/Canvas_Tutorial/Bilder
translation_of: Web/API/Canvas_API/Tutorial/Using_images
---
<p>{{CanvasSidebar}}</p>

<p>Natürlich können auch Bilder gezeichnet werden. Diese können die unterschiedlichsten Formate haben: PNG, GIF, JPEG oder bestimmte HTML Elemente.</p>

<p>Um Bilder zu importieren bedarf es bloß zwei Schritte:</p>

<ol>
 <li>Ein {{domxref("HTMLImageElement")}} Objekt erzeugen oder das HTML Element selektieren.</li>
 <li>Das Bild mithilfe der <code>drawImage()</code> Funktion zeichnen.</li>
</ol>

<h2 id="Bilder_importieren">Bilder importieren</h2>

<p>Die canvas API unterstützt folgende Typen als Bilder:</p>

<dl>
 <dt>{{domxref("HTMLImageElement")}}</dt>
 <dd>Diese Bilder können mithilfe des <code>Image()</code> Konstruktor oder mithilfe eines {{HTMLElement("img")}} Element erstellt werden.</dd>
 <dt>{{domxref("HTMLVideoElement")}}</dt>
 <dd>Der aktuelle Frame des {{HTMLElement("video")}} Element wird als Bild genutzt.</dd>
 <dt>{{domxref("HTMLCanvasElement")}}</dt>
 <dd>Ein anderes {{HTMLElement("canvas")}} Element kann ebenfalls als Bild dienen.</dd>
 <dt>{{domxref("ImageBitmap")}}</dt>
 <dd>Eine hochleistungsfähige Bitmap, welche mit niedriger Verzögerung gerendert werden kann. Sie lässt sich aus allen der oben genannten Quellen, sowie aus mehreren weitern erstellen.</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="Bilder_von_derselben_Seite">Bilder von derselben Seite</h3>

<p>Um Bilder von derselben Seite zu bekommen, können diese Methoden genutzt werden:</p>

<ul>
 <li>Die {{domxref("document.images")}} Sammlung</li>
 <li>Die {{domxref("document.getElementsByTagName()")}} Methode</li>
 <li>Die {{domxref("document.getElementById()")}} Methode, wenn eine Id festgelegt worden ist</li>
</ul>

<h3 id="Bilder_von_anderen_Seiten_nutzen">Bilder von anderen Seiten nutzen</h3>

<p>Mithilfe des {{htmlattrxref("crossorigin", "img")}} Attributs eines {{domxref("HTMLImageElement")}} ist es möglich die Erlaubnis zur Benutzung eines Bildes von einer anderen Domain zu nutzen. Wenn die Domain jenen Zugriff gestattet, kann das Image genutzt werden und das Bild wird wie gewollt angezeigt; andernfalls entsteht ein <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image#What_is_a_.22tainted.22_canvas.3F">"getaintes Canvas"</a>.</p>

<h3 id="Andere_Canvas_Elemente_benutzen">Andere Canvas Elemente benutzen</h3>

<p>Genau wie normalen Bildern auch, können wir ein anderes Canvas durch {{domxref("document.getElementsByTagName()")}} oder {{domxref("document.getElementById()")}} ansprechen.</p>

<p>Sei dabei sicher, dass du auf deinem Canvas etwas gezeichnet hast, bevor du es im Zielcanvas verwendest.</p>

<p>Eine sinnvoller Einsatz ist zum Beispiel das zweite Canvas als Vorschaubild (Thumbnail) des ersten zu verwenden.</p>

<h3 id="Ein_Bild_von_Grund_auf">Ein Bild von Grund auf</h3>

<p>Eine andere Option ist ein neues {{domxref("HTMLImageElement")}} in JavaScript zu erstellen. Um das zu tun, können wir den <code>Image()</code>-Konstruktor verwenden:</p>

<pre class="brush: js"><code>var img = new Image(); // Erstelle neues Image-Objekt
img.src = 'myImage.png'; // Setze den Pfad zum Bild</code></pre>

<p>Wird dieses Skript ausgeführt, fängt das Bild an zu laden.</p>

<div class="note">
<p><strong>Achtung</strong>: Wenn <code>drawImage()</code> vor dem Laden des Bildes ausgeführt wird, wird nichts passieren (In älteren Browsern kann es eine Fehlermeldung geben). Um jenen Fehler zu vermeiden, muss also sichergestellt werden, dass das load-Event benutzt wird.</p>
</div>

<pre class="brush: js"><code>var img = new Image();   // Erstelle neues Image-Objekt
img.addEventListener("load", function() {
  // füge hier den drawImage()-Befehl ein
}, false);
img.src = 'myImage.png'; // Setze den Pfad zum Bild
</code></pre>

<p>Wenn nur ein externes Bild geladen werden muss, ist das eine gute Möglichkeit. Wenn jedoch mehrere Bilder benötigt werden, sollte es besser anders gelöst werden. Es ist nicht das Ziel deises Tutorials auf das Vorladen von Bildern einzugehen, aber für eine komplette Lösung kannst du dir <a href="http://www.webreference.com/programming/javascript/gr/column3/">JavaScript Image Preloader</a> angucken (ist leder auf Englisch).</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/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_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><code>drawImage(<em>image</em>, <em>x</em>, <em>y</em>)</code></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>

<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">&lt;html&gt;
 &lt;body onload="draw();"&gt;
   &lt;canvas id="canvas" width="180" height="150"&gt;&lt;/canvas&gt;
 &lt;/body&gt;
&lt;/html&gt;
</pre>
</div>

<pre class="brush: js">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><code>drawImage(<em>image</em>, <em>x</em>, <em>y</em>, <em>width</em>, <em>height</em>)</code></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">&lt;html&gt;
 &lt;body onload="draw();"&gt;
   &lt;canvas id="canvas" width="150" height="150"&gt;&lt;/canvas&gt;
 &lt;/body&gt;
&lt;/html&gt;
</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&lt;4;i++){
      for (var j=0;j&lt;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. It lets us cut out a section of the source image, then scale and draw it on our canvas.</p>

<dl>
 <dt><code>drawImage(<em>image</em>, <em>sx</em>, <em>sy</em>, <em>sWidth</em>, <em>sHeight</em>, <em>dx</em>, <em>dy</em>, <em>dWidth</em>, <em>dHeight</em>)</code></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">&lt;html&gt;
 &lt;body onload="draw();"&gt;
   &lt;canvas id="canvas" width="150" height="150"&gt;&lt;/canvas&gt;
   &lt;div style="display:none;"&gt;
     &lt;img id="source" src="https://mdn.mozillademos.org/files/5397/rhino.jpg" width="300" height="227"&gt;
     &lt;img id="frame" src="https://mdn.mozillademos.org/files/242/Canvas_picture_frame.png" width="132" height="150"&gt;
   &lt;/div&gt;
 &lt;/body&gt;
&lt;/html&gt;
</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 arround 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">&lt;html&gt;
 &lt;body onload="draw();"&gt;
     &lt;table&gt;
      &lt;tr&gt;
        &lt;td&gt;&lt;img src="https://mdn.mozillademos.org/files/5399/gallery_1.jpg"&gt;&lt;/td&gt;
        &lt;td&gt;&lt;img src="https://mdn.mozillademos.org/files/5401/gallery_2.jpg"&gt;&lt;/td&gt;
        &lt;td&gt;&lt;img src="https://mdn.mozillademos.org/files/5403/gallery_3.jpg"&gt;&lt;/td&gt;
        &lt;td&gt;&lt;img src="https://mdn.mozillademos.org/files/5405/gallery_4.jpg"&gt;&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td&gt;&lt;img src="https://mdn.mozillademos.org/files/5407/gallery_5.jpg"&gt;&lt;/td&gt;
        &lt;td&gt;&lt;img src="https://mdn.mozillademos.org/files/5409/gallery_6.jpg"&gt;&lt;/td&gt;
        &lt;td&gt;&lt;img src="https://mdn.mozillademos.org/files/5411/gallery_7.jpg"&gt;&lt;/td&gt;
        &lt;td&gt;&lt;img src="https://mdn.mozillademos.org/files/5413/gallery_8.jpg"&gt;&lt;/td&gt;
      &lt;/tr&gt;
     &lt;/table&gt;
     &lt;img id="frame" src="https://mdn.mozillademos.org/files/242/Canvas_picture_frame.png" width="132" height="150"&gt;
 &lt;/body&gt;
&lt;/html&gt;
</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&lt;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, "https://mdn.mozillademos.org/files/205/Canvas_art_gallery.jpg")}}</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 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="js">ctx.mozImageSmoothingEnabled = false;
</pre>

<p>{{PreviousNext("Web/Guide/HTML/Canvas_tutorial/Drawing_shapes", "Web/Guide/HTML/Canvas_tutorial/Applying_styles_and_colors")}}</p>