docs.rodeo

MDN Web Docs mirror

CanvasRenderingContext2D: drawImage() method

{{APIRef}} 

The CanvasRenderingContext2D.drawImage() method of the Canvas 2D API provides different ways to draw an image onto the canvas.

Syntax

drawImage(image, dx, dy)
drawImage(image, dx, dy, dWidth, dHeight)
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

drawImage

Parameters

Return value

None ({{jsxref("undefined")}} ).

Exceptions

Examples

Drawing an image to the canvas

This example draws an image to the canvas using the drawImage() method.

HTML

<canvas id="canvas"></canvas>
<div style="display:none;">
  <img
    id="source"
    src="https://mdn.github.io/shared-assets/images/examples/rhino.jpg"
    width="300"
    height="227" />
</div>

JavaScript

The source image is taken from the coordinates (33, 71), with a width of 104 and a height of 124. It is drawn to the canvas at (21, 20), where it is given a width of 87 and a height of 104.

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const image = document.getElementById("source");

image.addEventListener("load", (e) => {
  ctx.drawImage(image, 33, 71, 104, 124, 21, 20, 87, 104);
});

Result

{{ EmbedLiveSample('Drawing_an_image_to_the_canvas', 700, 180) }} 

Understanding source element size

The drawImage() method uses the source element’s intrinsic size in CSS pixels when drawing.

For example, if you load an Image and specify the optional size parameters in its constructor, you will have to use the naturalWidth and naturalHeight properties of the created instance to properly calculate things like crop and scale regions, rather than element.width and element.height. The same goes for videoWidth and videoHeight if the element is a {{htmlelement("video")}}  element, and so on.

HTML

<canvas id="canvas"></canvas>

JavaScript

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

const image = new Image(60, 45); // Using optional size for image
image.onload = drawImageActualSize; // Draw when image has loaded

// Load an image of intrinsic size 300x227 in CSS pixels
image.src = "https://mdn.github.io/shared-assets/images/examples/rhino.jpg";

function drawImageActualSize() {
  // Use the intrinsic size of image in CSS pixels for the canvas element
  canvas.width = this.naturalWidth;
  canvas.height = this.naturalHeight;

  // Will draw the image as 300x227, ignoring the custom size of 60x45
  // given in the constructor
  ctx.drawImage(this, 0, 0);

  // To use the custom size we'll have to specify the scale parameters
  // using the element's width and height properties - lets draw one
  // on top in the corner:
  ctx.drawImage(this, 0, 0, this.width, this.height);
}

Result

{{EmbedLiveSample('Understanding_source_element_size', 700, 260)}} 

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

Notes

See also

In this article

View on MDN