The HTML5 Canvas provides you with the ability to draw lines, shapes, text, and images as well In this tutorial, we will cover the drawImage()
method and show some examples of how this method can be used to draw images onto the HTML5 canvas.
Usage
To draw an image onto the HTML5 Canvas, we can use the drawImage()
method which requires an image object and a destination point. The destination point is relative to the top left corner of the image. The drawImage()
method requires an image object. In our JavaScript block, we must create an image and once it is loaded, we draw the image onto the HTML5 canvas.
Syntax
Draw the image onto the canvas.
context.drawImage(img,x,y);
Draw the image on the canvas, and specify the width and height of the image.
context.drawImage(img,x,y,width,height);
Crop the image and draw the cropped portion on the canvas.
context.drawImage(img,cx,cy,cwidth,cheight,x,y,width,height);
Parameter | Description |
---|---|
img | Specifies the image to use |
sx | Optional. The x coordinate where to start cropping |
sy | Optional. The y coordinate where to start cropping |
swidth | Optional. Width of the cropping image |
sheight | Optional. Height of the cropping 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 |
height | Optional. The height of the image to use |
Examples
The first example is the most basic one where the image is simply drawn on the canvas element. The second example will draw the image according to the dimensions provided. The third example crops the image and draws the results.
<canvas id="myCanvas" width="287" height="374">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function () {
context.drawImage(imageObj, 10, 10);
};
imageObj.src = 'monalisa.jpg'
</script>
Draw the image on the canvas, and specify width and height of the image.
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function () {
context.drawImage(imageObj, 60, 60, 167, 254);
};
imageObj.src = 'monalisa.jpg'
</script>
Crop the image and draw the cropped portion on the canvas.
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function () {
context.drawImage(imageObj, 70, 5, 125 ,125, 19, 62, 250, 250);
};
imageObj.src = 'monalisa.jpg'
</script>