在学习h5的时候,canvas标签中getImageData()报错:security error!
具体代码如下(chrome浏览器):
function createGSCanvas(img){ var canvas=document.createElement("canvas"); canvas.width=img.width; canvas.height=img.height; var ctx=canvas.getContext("2d"); ctx.drawImage(img,0,0); var c=ctx.getImageData(0,0,img.width,img.height); for(var i=0;i<c.height;i++){ for(var j=0;j<c.width;j++){ var x=(i*4)*c.height+(j*4); var r=c.data[x]; var g=c.data[x+1]; var b=c.data[x+2]; c.data[x]=c.data[x+1]=c.data[x+2]=(r+g+b)/3; } } ctx.putImageData(c,0,0,0,0,c.width,c.height); return canvas.toDataURL(); }
报错信息如下:Uncaught SecurityError: Failed to execute ‘getImageData‘ on ‘CanvasRenderingContext2D‘: The canvas has been tainted by cross-origin data.
原因:createGSCanvas()调用了getImageData函数,但是图片存储在本地文件,默认为没有域名,chrome浏览器判定为跨域才报错!
解决方法:1、将图片放置在服务器中,由服务器返回给客户端浏览器,遵循同源策略;
2、在IE、Firefox浏览器中打开。
时间: 2024-10-08 10:44:27