9

I want to draw a image on canvas where the source for image will be set dynamically by user.I am getting following error while trying to set src for image:

Not allowed to load local resource: file:///D:/My%20Picsb.jpg'

Is there any way to load file from local drives to draw them on a canvas?

var img = new Image();
img.onload = function () {  
    context.drawImage(img, 20, 20, 50, 50);
};

img.src = "D:\My Pics\tb.jpg";
display-name-is-missing
  • 4,424
  • 5
  • 28
  • 41
hampi2017
  • 701
  • 2
  • 13
  • 33

3 Answers3

15

What you want won't work because of security reasons. What you could do, however, is adding a file input field and upload it to the canvas, like this:

HTML

<input type="file" id="file_input">

JS

$("#file_input").change(function(e){


    var URL = window.webkitURL || window.URL;
    var url = URL.createObjectURL(e.target.files[0]);
    var img = new Image();
    img.src = url;


    img.onload = function() {

            img_width = img.width;
            img_height = img.height;

            context.drawImage(img, 0, 0, img_width, img_height);

    }


});

I had the same problem as you not so long ago, and this code did the job when it comes to loading local images onto a canvas. I would however also recommend to eventually resize the image, so that it fits into the canvas. I used the following code (replace 460 with the size of your canvas).

var new_x = 0;
var new_y = 0;

if (img_width > img_height) {
    new_x = 460;
    new_y = (460*img_height)/img_width;
} 

else if (img_height > img_width) {
    new_x = (460*img_width)/img_height;
    new_y = 460;
}

else {
    new_x = 460;
    new_y = 460;
}

context.drawImage(img, 0, 0, new_x, new_y);
display-name-is-missing
  • 4,424
  • 5
  • 28
  • 41
0

I had the need for similar functionality and solved it using ajax by uploading the image temporarily to the server and setting the src attribute of the target img to that temporary file name. You can complete the task by creating a cron job that deletes those temporary images from your server's directory.

jjyepez
  • 352
  • 3
  • 7
-3

No. JavaScript has security block of accessing local files, whether it be reading or writing. Put the file on a webserver ( best on the same domain, because of cross domain issues ).

Because your user should provide for the file you have to code a file upload solution. Reference the internet on how to do that.

yunzen
  • 32,854
  • 11
  • 73
  • 106
  • 3
    Just saying...You're referencing Cross-Origin security (CORS), but CORS doesn't restrict loading a local image if the user initiates the fetch. The user can initiate the fetch by (1) activating an html input-type-file element or (2) by actively dragging a local image into a dropzone div which uses FileReader to get the image's dataURL. BTW, I didn't ding you with the downvote. Cheers! – markE Feb 09 '14 at 17:36