CanvasRenderingContext2D.drawImage() - Web APIs | MDN

  1. References
  2. Web APIs
  3. CanvasRenderingContext2D
  4. drawImage()
Article Actions
  • English (US)
    • Remember language
    • Deutsch
    • Español
    • Français
    • 日本語
    • Русский
    • 中文 (简体)
  • Syntax
  • Examples
  • Specifications
  • Browser compatibility
  • Notes
  • See also
  1. CanvasRenderingContext2D
  2. Instance properties
    1. canvas
    2. direction
    3. fillStyle
    4. filter
    5. font
    6. fontKerning
    7. fontStretch
    8. fontVariantCaps
    9. globalAlpha
    10. globalCompositeOperation
    11. imageSmoothingEnabled
    12. imageSmoothingQuality
    13. letterSpacing
    14. lineCap
    15. lineDashOffset
    16. lineJoin
    17. lineWidth
    18. miterLimit
    19. shadowBlur
    20. shadowColor
    21. shadowOffsetX
    22. shadowOffsetY
    23. strokeStyle
    24. textAlign
    25. textBaseline
    26. textRendering
    27. wordSpacing
  3. Instance methods
    1. arc()
    2. arcTo()
    3. beginPath()
    4. bezierCurveTo()
    5. clearRect()
    6. clip()
    7. closePath()
    8. createConicGradient()
    9. createImageData()
    10. createLinearGradient()
    11. createPattern()
    12. createRadialGradient()
    13. drawFocusIfNeeded()
    14. drawImage()
    15. ellipse()
    16. fill()
    17. fillRect()
    18. fillText()
    19. getContextAttributes()
    20. getImageData()
    21. getLineDash()
    22. getTransform()
    23. isContextLost()
    24. isPointInPath()
    25. isPointInStroke()
    26. lineTo()
    27. measureText()
    28. moveTo()
    29. putImageData()
    30. quadraticCurveTo()
    31. rect()
    32. reset()
    33. resetTransform()
    34. restore()
    35. rotate()
    36. roundRect()
    37. save()
    38. scale()
    39. setLineDash()
    40. setTransform()
    41. stroke()
    42. strokeRect()
    43. strokeText()
    44. transform()
    45. translate()
  • Syntax
  • Examples
  • Specifications
  • Browser compatibility
  • Notes
  • See also

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

Syntax

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

drawImage

Parameters

image

An element to draw into the context. The specification permits any canvas image source, specifically, an HTMLImageElement, an SVGImageElement, an HTMLVideoElement, an HTMLCanvasElement, an ImageBitmap, an OffscreenCanvas, or a VideoFrame.

sx Optional

The x-axis coordinate of the top left corner of the sub-rectangle of the source image to draw into the destination context. Use the 3- or 5-argument syntax to omit this argument.

sy Optional

The y-axis coordinate of the top left corner of the sub-rectangle of the source image to draw into the destination context. Use the 3- or 5-argument syntax to omit this argument.

sWidth Optional

The width of the sub-rectangle of the source image to draw into the destination context. If not specified, the entire rectangle from the coordinates specified by sx and sy to the bottom-right corner of the image is used. Use the 3- or 5-argument syntax to omit this argument. A negative value will flip the image.

sHeight Optional

The height of the sub-rectangle of the source image to draw into the destination context. Use the 3- or 5-argument syntax to omit this argument. A negative value will flip the image.

dx

The x-axis coordinate in the destination canvas at which to place the top-left corner of the source image.

dy

The y-axis coordinate in the destination canvas at which to place the top-left corner of the source image.

dWidth

The width to draw the image in the destination canvas. This allows scaling of the drawn image. If not specified, the image is not scaled in width when drawn. Note that this argument is not included in the 3-argument syntax.

dHeight

The height to draw the image in the destination canvas. This allows scaling of the drawn image. If not specified, the image is not scaled in height when drawn. Note that this argument is not included in the 3-argument syntax.

Return value

None (undefined).

Exceptions

InvalidStateError DOMException

Thrown when the image has no image data or if the canvas or source rectangle width or height is zero.

TypeMismatchError DOMException

Thrown when a null or undefined image is passed as parameter.

Examples

Drawing an image to the canvas

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

HTML

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.

jsconst 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

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 <video> element, and so on.

HTML

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

JavaScript

jsconst 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

Specifications

Specification
HTML Standard # dom-context-2d-drawimage-dev

Browser compatibility

BCD tables only load in the browser

Notes

  • drawImage() only works correctly on an HTMLVideoElement when its HTMLMediaElement.readyState is greater than 1 (i.e., seek event fired after setting the currentTime property).
  • drawImage() will always use the source element's intrinsic size in CSS pixels when drawing, cropping, and/or scaling.
  • In some older browser versions, drawImage() will ignore all EXIF metadata in images, including the Orientation. This behavior is especially troublesome on iOS devices. You should detect the Orientation yourself and use rotate() to make it right.

See also

  • The interface defining this method: CanvasRenderingContext2D

Help improve MDN

Was this page helpful to you?YesNoLearn how to contribute.

This page was last modified on Aug 27, 2024 by MDN contributors.

View this page on GitHub • Report a problem with this content

Từ khóa » Html Canvas Stretch Image