HTML and CSS Reference
In-Depth Information
</script>
</body>
</html>
We drew the image to the canvas using the method
context.drawImage
, which takes an image element
and an x and y position on the canvas. This code is placed within the
image.onload
callback; otherwise,
the command would have executed
before
the image loaded, rendering nothing.
The
context.drawImage
method can be invoked in three ways, using multiple arguments:
drawImage(image, dx, dy)
: Draws an image at the canvas position (
dx
,
dy
), which is the
upper-left corner of the image.
drawImage(image, dx, dy, dw, dh)
: Scales the image using
dw
for width and
dh
for height
and draws it to the canvas position (
dx
,
dy)
.
drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
: Clips an image to the rectangle (
sx
,
sy
,
sw
,
sh
), scales it to (
dh
,
dw
), and draws it at position (
dx
,
dy
).
Using image elements
You can also access an image element in your HTML document using the DOM. This has the advantage
of already loading the image by the time the script gets to it. If you do it this way, use some CSS to hide
the image element or you might see it rendered twice in your document. Here's the completed example
(
11-embed-image.html
):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Embed Image</title>
<link rel="stylesheet" href="style.css">
<style>
#picture {
display: none;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<img id="picture" src="picture.jpg">
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
image = document.getElementById('picture');
context.drawImage(image, 0, 0);
};
</script>
</body>
</html>