HTML canvas drawImage() Method

Introduction

Draw the image onto the canvas:

View in separate window

<!DOCTYPE html>
<html>
<body>

<p>Image to use:</p>
<img id="scream" src="image1.png" alt="the circle" width="100" height="100">

<p>Canvas:</p>
<canvas id="myCanvas" width="250" height="300" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 10, 10);
</script>//w ww  . jav a  2 s  . c  o m

</body>
</html>

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

The drawImage() method can also draw parts of an image, and/or increase/reduce the image size.

Position the image on the canvas:

context.drawImage(img, x, y);

Position the image on the canvas, and set width and height of the image:

context.drawImage(img, x, y, width, height);

Clip the image and position the clipped part on the canvas:

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

Parameter Values

Parameter Description
img Specifies the image, canvas, or video element to use
sxOptional. The x coordinate where to start clipping
syOptional. The y coordinate where to start clipping
swidthOptional. The width of the clipped image
sheight Optional. The height of the clipped image
x The x coordinate where to place the image on the canvas
y The y coordinate where to place the image on the canvas
width Optional. The width of the image to use
heightOptional. The height of the image to use



PreviousNext

Related