Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

importing image on canvas html5

Tags:

html

image

canvas

var img = new Image();
img.src = '/images/backdrop.jpg';
ctx.drawImage(img,0,0);

I wanted to load an image from local disk on to canvas using dialog box mechanism rather than the path directly specified as in above example. I tried different sorts using JavaScript but in vain, even tried using the input type as file. What else can I try?

like image 623
Nitesh Avatar asked Dec 28 '22 06:12

Nitesh


1 Answers

Take a look here:

  • https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images

It's important to have drawImage call after the image has loaded:

var img = new Image();
img.onload = function() {
    var ctx = document.getElementById('ctx').getContext('2d');
    ctx.drawImage(img, 0, 0);
}
img.src = 'images/backdrop.jpg';

Also, note that you probably want to use images/backdrop.jpg instead of /images/backdrop.jpg (note there's no slash in front), as using the latter would get the image from root directory, I would assume that's probably not where your images are.

As far as loading from a dialog box, you can replace the last line from the above with something like this:

var name = prompt("Enter the name of the file", "backdrop.jpg");
img.src = 'images/' + name;

This way, the user would be able to enter the name of the image file to load it. Of course, you need to have that file in your images folder.

Hope this helps.

like image 97
icyrock.com Avatar answered Jan 12 '23 19:01

icyrock.com