Advertisement
Home Open Editor ❯

HTML canvas drawImage() Method

Example

<p>Image:</p>
<img id="demo" width="50" height="50" src="smiley.png" alt="Smiley">

<p>Canvas:</p>
<canvas id="myCanvas" width="50" height="50" style="border:1px dashed black;">
  Your browser does not support the HTML5 canvas tag.
</canvas>

<br><button onclick="myFunction()">Click me!</button>

<script>
function myFunction() {
  let c = document.getElementById("myCanvas");
  let ctx = c.getContext("2d");
  let img = document.getElementById("demo");
  ctx.drawImage(img, 8, 8);
}
</script>

Try this code ❯

Meaning

The drawImage() method draws an image, canvas, or video onto the canvas.


Standard Syntax

JavaScript syntax:

context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);


Advertisement

Parameter Values

Parameter Description
img Specifies the image, canvas, or video element to use.
sx Optional. Specifies the x coordinate where to start clipping.
sy Optional. Specifies the y coordinate where to start clipping.
swidth Optional. Specifies the width of the clipped image
sheight Optional. Specifies the height of the clipped image.
x Specifies the x coordinate where to place the image on the canvas.
y Specifies the y coordinate where to place the image on the canvas.
width Optional. Specifies the width of the image to use.
height Optional. Specifies the height of the image to use.
Home Open Editor ❯
Advertisement