/

HTML / CSS / JavaScript Tutorial

JavaScript canvas2d object method: drawImage()

[this page | pdf | back links]

The drawImage() method of the JavaScript DOM object returned by the getContext("2d") method applied to the HTML <canvas> element draws an image, canvas or video onto the canvas.

 

There are three versions of the createImageData() method with the following formats and parameters (the ones with clip parameters involve pre-clipping of the image):

 

context.drawImage(image, x, y)

 

context.drawImage(image, x, y, width, height)

 

context.drawImage(image, clipx, clipy, clipwidth, clipheight, x, y, width, height)

 

Parameter

Required / Optional

Description

clipheight

Optional

Clip height

clipwidth

Optional

Clip width

clipx

Optional

Clip x-coordinate

clipy

Optional

Clip y-coordinate

height

Optional

Height of image to use (potentially stretching or squashing original image)

image

Required

Image / video / canvas to be inserted

width

Optional

Width of image to use (potentially stretching or squashing original image)

x

Required

x-coordinate of upper-left corner

y

Required

y-coordinate of upper-left corner

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head></head>
<body>
Image we will draw:<br>
<img id="shape" src="Pictures/Shape1and2.png"><br><br>
This image drawn onto a canvas<br>
<span id="element"></span>

<script>
var x2 = document.createElement("CANVAS");
x2.setAttribute("width", "250");
x2.setAttribute("height", "110");
x2.setAttribute("style", "border: 1px solid black");
var c2 = x2.getContext("2d");

var img=document.getElementById("shape");
c2.drawImage(img,30,5);

document.getElementById("element").appendChild(x2);
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodCanvas2dDrawImage() {
  var x = document.createElement("CANVAS"); var c = x.getContext("2d"); return !!c.drawImage;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)


Desktop view | Switch to Mobile