PageResource.com - Web Development Tutorials

Insert Image in Canvas

You can place images inside the canvas element. Unlike the <div> element you can’t use a <img> tag. Instead you have to use JavaScript to place the image inside the canvas element. We have to use the drawImage() method to set the position of the image inside the canvas element.

Here is the script

<script>
window.onload = function() {
var canvas=document.getElementById("drawing"); // grabs the canvas element
var context=canvas.getContext("2d"); // returns the 2d context object
var img=new Image() //creates a variable for a new image
 
img.src= "images/vft.jpg" // specifies the location of the image
context.drawImage(img,20,20); // draws the image at the specified x and y location
}
</script>

Here is what it looks like in the browser

Leave a Reply


Copyright © The Web Design Resource. All rights reserved. | Contact Us | Privacy Policy