How to load an image into a canvas?

Member

by denis , in category: Javascript , 2 months ago

How to load an image into a canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 2 months ago

@denis 

To load an image into a canvas using HTML5 and JavaScript, you can follow the steps below:

  1. Create an HTML canvas element in your HTML file:
1
<canvas id="myCanvas" width="400" height="400"></canvas>


  1. Create a JavaScript function to load the image into the canvas:
1
2
3
4
5
6
7
8
9
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

const img = new Image();
img.src = 'path/to/image.jpg';

img.onload = function() {
  ctx.drawImage(img, 0, 0);
};


  1. Make sure to replace path/to/image.jpg with the actual path to your image file.
  2. Make sure to call the JavaScript function after the page loads to ensure that the image is loaded into the canvas:
1
2
3
window.onload = function() {
  // Call the function to load image into canvas
};


With these steps, you should be able to load an image into a canvas on your webpage using HTML5 and JavaScript.