HTML Canvas Images
HTML Canvas - Draw Image
The drawImage()
method draws an image onto
the canvas.
The drawImage()
method can be used with three different syntaxes:
drawImage(image, dx, dy)
drawImage(image, dx, dy, dwidth, dheight)
drawImage(image, sx, sy, swidth, sheight, dx, dy, dwidth, dheight)
The examples below explain the three different syntaxes.
drawImage(image, dx, dy)
The drawImage(image, dx, dy)
syntax positions the image on the canvas.
Example
Draw image in position (10, 10) on the canvas:
<script>
const canvas = document.getElementById("myCanvas");
const ctx =
canvas.getContext("2d");
const image = document.getElementById("scream");
image.addEventListener("load", (e) => {
ctx.drawImage(image, 10,
10);
});
</script>
Try it Yourself »
drawImage(image, dx, dy, dwidth, dheight)
The drawImage(image, dx, dy, dwidth, dheight)
syntax positions the image on the canvas, and specifies
the width and height of the image on the canvas.
Example
Draw image in position (10, 10) on the canvas, with a width and height of 80 pixels:
<script>
const canvas = document.getElementById("myCanvas");
const ctx =
canvas.getContext("2d");
const image = document.getElementById("scream");
image.addEventListener("load", (e) => {
ctx.drawImage(image, 10,
10, 80, 80);
});
</script>
Try it Yourself »
drawImage(image, sx, sy, swidth, sheight, dx, dy, dwidth, dheight)
The drawImage(image, sx, sy, swidth, sheight, dx, dy, dwidth, dheight)
syntax
is used to clip the source image, before it is placed on the canvas.
Example
Here we clip the source image from position (90, 130), with a width of 50 and a height of 60, and then position the clipped part on the canvas in position (10, 10), with a width and height of 150 and 160 pixels (so the clipped source image will also be scaled/stretched:
<script>
const canvas = document.getElementById("myCanvas");
const ctx =
canvas.getContext("2d");
const image = document.getElementById("scream");
image.addEventListener("load", (e) => {
ctx.drawImage(image,
90, 130, 50, 60, 10, 10, 150, 160);
});
</script>
Try it Yourself »
Here are the parameters of the drawImage()
method:
Parameter | Description |
---|---|
image | Required. The image to draw into the context |
sx | Optional. The x-coordinate of the top-left corner of the source image (for clipping the source image) |
sy | Optional. The y-coordinate of the top-left corner of the source image (for clipping the source image) |
swidth | Optional. The width of the clipping of the source image, in pixels |
sheight | Optional. The height of the clipping of the source image, in pixels |
dx | The x-coordinate in the canvas where to place the top-left corner of the source image |
dy | The y-coordinate in the canvas where to place the top-left corner of the source image |
dwidth | Optional. The width to draw the image in the destination canvas. This allows scaling of the image |
dheight | Optional. The height to draw the image in the destination canvas. This allows scaling of the image |