问题
I am trying to manually set the img src to a path on the filesystem, and then I want to draw that image on a canvas. I am using:
var curr_canv = document.getElementById('c_main').getContext('2d');
var img = new Image();
img.width = 525;
img.height = 400;
img.src = "..\AAAA\BBBB\CCCC\myimage.jpg";
curr_canv.drawImage(img,0,0);
But nothing is drawn on the canvas after I do this. Any thoughts?
回答1:
You need to set the path to an absolute path within your webserver.
Javascript in the browser has no access to any filesystem.
回答2:
You are using
\
(backslash)
instead of
/
(forward-slash).
JavaScript uses \
as an escape character.
回答3:
Yeah the path has to be in the web folder or another accessible path. You can see that you code works in general here: http://jsfiddle.net/pwm36/8/
回答4:
The short answer is "You can't do that." Javascript running in a browser has no direct access to the user's file system. This is a security feature of browsers in general.
There is a relatively new FileSystem API for HTML5, but it still probably doesn't give you what you want, because the browser is still "jailed". You can't reach any files outside of the directory set aside by the browser.
You might consider the drag-and-drop API. Users can drop files onto an area you designate, and I think you can access it with Javascript at that point.
回答5:
Like other have said you need to use a webserver delivered image. Or use the "file://" protocol.
Be carefull, loading an image ins an asynchronous tack you fant to draw only after the image has been loaded.
img.onload = function() {
curr_canv.drawImage(img,0,0);
}
See the MDN for more info.
来源:https://stackoverflow.com/questions/12413546/javascript-setting-img-src-with-absolute-path