Draw an image using the HTML <canvas> Tag
<h2>Original Image</h2> <img id="glacier" src="http://www.htmlcodes.ws/images/examples/3s.jpg" alt="Photo of Rob Roy Glacier"> <h2>Canvas Images</h2> <canvas id="myCanvas" width="350" height="220"> <p>Fallback content for browsers that don't support the canvas tag.</p> </canvas> <script> var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); // Original size ctx.drawImage(glacier,5,25); // Resized ctx.drawImage(glacier,180,0,100,75); // Clipped ctx.drawImage(glacier,20,35,85,70,190,130,85,70); </script>
The above example demonstrates how to draw an image using the HTML
First, we draw the image to the canvas using the original dimensions of the source image. We then draw the image again, but this time, we resize it by specifying the width and height dimensions. The third canvas image has been clipped from the original, then that clipping has been drawn to the canvas in the size that we specify.
Drawing an image to a
<canvas> element, is done using the
drawImage() method. This method can be invoked with three different sets of arguments.
drawImage(image, dx, dy)
- This is
drawImage()at its simplest. The
imageparameter is used to specify the image. It can refer to an
dxargument is used to specify the horizontal coordinates of the destination canvas image. The
dyrepresents the vertical coordinates.
drawImage(image, dx, dy, dw, dh)
- You can add
dwto specify the width of the destination canvas image, and
dhto specify the height.
drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
- This is used for clipping a part of the source image and drawing that to the canvas. The
shparameters allow you to specify which part of the source image to clip. The
dhparameters allow you to specify where the result of that clipping will appear on the canvas, as well as its dimensions.