How to set a default image to a canvas?

by scotty_walker , in category: Javascript , 5 months ago

How to set a default image to a canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , 5 months ago

@scotty_walker 

To set a default image to a canvas, you can follow these steps:

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


  1. Create a JavaScript function that will draw the default image on the canvas:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function drawDefaultImage() {
  var canvas = document.getElementById('myCanvas');
  var ctx = canvas.getContext('2d');
  
  var img = new Image();
  img.src = 'default-image.jpg';
  
  img.onload = function() {
    ctx.drawImage(img, 0, 0);
  };
}


  1. Call the drawDefaultImage function when the page loads:
1
2
3
window.onload = function() {
  drawDefaultImage();
}


  1. Make sure to replace 'default-image.jpg' with the path to your default image.


By following these steps, the default image will be displayed on the canvas when the page loads.