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
479 views
in Technique[技术] by (71.8m points)

html - context.getImageData() on localhost?

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

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

1 Reply

0 votes
by (71.8m points)

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.


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

...