Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
904 views
in Technique[技术] by (71.8m points)

html - importing image on canvas html5

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Take a look here:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...