1. Loading Images:

 

Before we can display images on the canvas, we need to load them into our web page. Images can be loaded using the <img> tag in HTML or programmatically using JavaScript. Here's an example of loading an image using JavaScript:



const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const img = new Image();

img.onload = function() {
    // Once the image is loaded, draw it on the canvas
    ctx.drawImage(img, 0, 0);
};

img.src = 'image.jpg'; // Set the image source
 



In this example:
 
  • We create an <img> element using new Image().
  • We set the onload event handler to execute a function when the image is fully loaded.
  • Inside the onload function, we use ctx.drawImage(img, 0, 0) to draw the image on the canvas.
  • Finally, we set the src attribute of the image to the image file path, triggering the image loading process.



2. Displaying Images on the Canvas:

 

The drawImage method is used to display images on the canvas. It can be used in various ways depending on the parameters passed to it.



Here are some common scenarios:


a. Displaying an Entire Image:

 

ctx.drawImage(img, 0, 0);
This code snippet draws the entire image starting from the top-left corner of the canvas (coordinates 0,0).
 



b. Displaying a Cropped Image:
 

ctx.drawImage(img, 50, 50, 100, 100, 0, 0, 100, 100);
 

In this example, we draw a cropped portion (100x100 pixels) of the image starting from coordinates (50,50) on the image and place it at coordinates (0,0) on the canvas.



c. Scaling Images:

 

ctx.drawImage(img, 0, 0, img.width / 2, img.height / 2);
 

This code snippet scales the image to half its original size before drawing it on the canvas. The parameters img.width / 2 and img.height / 2 specify the new width and height of the image.



Example with Explanation:

 

Let's put it all together in a complete example:



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas Image Example</title>
</head>
<body>
<canvas id="myCanvas" width="400" height="300"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const img = new Image();

img.onload = function() {
    // Draw the entire image
    ctx.drawImage(img, 0, 0);

    // Draw a cropped portion of the image
    ctx.drawImage(img, 50, 50, 100, 100, 200, 0, 100, 100);

    // Scale the image and draw it
    ctx.drawImage(img, 0, 0, img.width / 2, img.height / 2, 0, 200, 200, 150);
};

img.src = 'image.jpg'; // Path to your image file
</script>
</body>
</html>
 





In this example:
 
  • We create an HTML canvas with the ID myCanvas.
  • We load an image using JavaScript (img.src = 'image.jpg';).
  • Once the image is loaded (img.onload), we use ctx.drawImage to display the entire image, a cropped portion, and a scaled version on the canvas.

 



Practice Excercise Practice now