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

javascript - getImageData cross-origin error

Precursor: I know there have been a few questions already asked about this topic, but none of them seem to offer a straight JavaScript only solution.

So I ran into this error where I am trying to get the pixel data from a canvas using something like context.getImageData(), my exact code can been seen here or below:

<canvas id="imageCanvas" width="600" height="800"></canvas>
// Load Image
var canvas = document.getElementById('imageCanvas');

var image = new Image();
image.src = 'http://emoticons.pw/emoticons/emoticon-faces-002-medium.png';
image.onload = function() {

    width=image.width;
    height=image.height;

    var context = canvas.getContext('2d');
    context.fillStyle="#024359"; // canvas background color
    context.fillRect(0, 0, width, height);
    context.drawImage(this,0,0);

    imageData = context.getImageData(0,0,width, height); // PROBLEM HERE

    context.putImageData(imageData, 0, 0);
}

I get the following errors in Chrome:

Unable to get image data from canvas because the canvas has been tainted by cross-origin data.

and then a security error as well. I don't want to make server changes or start chrome with a weird instruction thing. I feel like there has to be something I can do in JavaScript.

Using local images only is not a problem, but when trying that, I got the same error!

I am trying to do this without a server, if I put this on my "default" godaddy web server, are all my problems solved? I heard rumors dropbox could also simulate a server close enough?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can't use file:// if you're using that (Chrome allow you to override this but I won't recommend it).

For local testing use a light-weight server such as Mongoose which allow you use http://localhost as a domain to test your local pages. This way you avoid problems with CORS.

If you need to host images on a different domain you need to make sure they support cross-origin usage.

DropBox and ImgUrl (I recommend the latter for just images) both support CORS usage, but you need to request such usage by adding the crossOrigin property to your image before setting the source (or include it in the HTML tag if you're using that):

var img = new Image;

img.onload = myLoader;
img.crossOrigin = '';              ///=anonymous
img.src = 'http://imgur.com/....';

or in HTML:

<img src="..." alt="" crossOrigin="anonymous" />

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

...