画布已被跨域数据工作污染 [英] canvas has been tainted by cross-origin data work around
问题描述
我正在编写脚本(或一起编辑和修改内容)来编辑页面上图像的外观.我知道 javascript 的基础知识,但这是我第一次看到画布.所以忍耐一下
im writing a script (or editing and hacking things together) to edit the look of images on a page. I know the basics of javascript but this is my first time looking at canvas. so bear with me
我收到此错误:
无法从画布中获取图像数据,因为画布已被跨域数据污染.
所以这是我抛出错误的代码片段:
so heres my code snippet throwing the error:
var canvas = document.createElement('canvas'),
context = canvas.getContext('2d'),
height = img.naturalHeight || img.offsetHeight || img.height,
width = img.naturalWidth || img.offsetWidth || img.width,
imgData;
canvas.height = height;
canvas.width = width;
context.drawImage(img, 0, 0);
console.log(context);
try {
imgData = context.getImageData(0, 0, width, height);
} catch(e) {}
现在我找到了这篇文章:
now i found this post :
http://bolsterweb.com/2012/06/grabbing-image-data-external-source-canvas-element/
但我不知道如何使它适合我的需要..
but i have no idea how to make it fit my needs..
出于安全考虑,我知道这一切 - 但是有没有办法让这一切发生?
I know its all due to security and all that - but is there a work around to make it all happen?
谢谢
编辑
哦,等等.. 错误是因为你不能 getImageData.. 所以有没有办法让它本地"
Oh wait.. the error is because you can't getImageData.. so is there away to make it 'local'
推荐答案
为了满足 CORS,您可以将图像托管在对 CORS 友好的网站上,例如 dropbox.com
To satisfy CORS, you can host your images on a CORS friendly site like dropbox.com
那么如果你指定 image.crossOrigin="anonymous" 就不会触发安全错误:
Then the security error will not be triggered if you speify image.crossOrigin="anonymous":
var image=new Image();
image.onload=function(){
}
image.crossOrigin="anonymous";
image.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/colorhouse.png";
这是代码和小提琴:http://jsfiddle.net/m1erickson/4djSr/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var image=new Image();
image.onload=function(){
ctx.drawImage(image,0,0);
// desaturation colors
var imgData=ctx.getImageData(0,0,canvas.width,canvas.height);
var data=imgData.data;
for(var i = 0; i < data.length; i += 4) {
var grayscale= 0.33*data[i]+0.5*data[i+1]+0.15*data[i+2];
data[i]=grayscale;
data[i+1]=grayscale;
data[i+2]=grayscale;
}
// write the modified image data
ctx.putImageData(imgData,0,0);
}
image.crossOrigin="anonymous";
image.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/colorhouse.png";
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=140 height=140></canvas>
</body>
</html>
这篇关于画布已被跨域数据工作污染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!