Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following snippet of code and I'm trying to run it from localhost (OSX, running XAMPP):

var canvas = document.getElementById('mycanvas');
    var cx = canvas.getContext('2d');

    var myImg = new Image();
    myImg.src = 'images/lion.jpg';

    $(myImg).load(function() {
        cx.drawImage(myImg, 0, 0);
        var imgData = cx.getImageData(0,0,150,150);
    });

But when I run it I get this error from the console:

Unable to get image data from canvas because the canvas has been tainted by cross-origin data.
site.js:11Uncaught Error: SECURITY_ERR: DOM Exception 18

I found some similar questions here and I know that this has something to do with the fact that I'm working locally and this wouldn't happen if I was trying to access the image from the same domain. I don't know if this makes sense, but it's what I understood.

My question is, how can I make this work in a local dev environment?

See Question&Answers more detail:os

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

1 Answer

Serve your html with an HTTP server, for example, Apache or Nginx.

Mac OSX comes with Python installed, so you can simply start an HTTP server by opening a terminal, then input:

cd /path/to/my/work/
python -m SimpleHTTPServer

Then open http://localhost:8000/ in your browser. This should work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...