我有以下问题:当我绘制一个矩形(使用 fillRect 方法),然后绘制一个图像(使用 drawImage)时,我无法使用 getImageData 从 Contex 获得正确的结果。当我用drawImage注释行时,它工作正常。问题出在哪里?
var img=document.getElementById("img");
var canvas=document.getElementById("can");
var ctx=canvas.getContext('2d');
ctx.fillStyle="red";
ctx.fillRect(0,0,50,50);
ctx.drawImage(img, 0, 0, 19, 19); //;(
var imgData=ctx.getImageData(0,0,50,50);
ctx.putImageData(imgData,100,100);
最佳答案
如果您查看控制台,它会告诉您错误:
Unable to get image data from canvas because the canvas has been tainted by cross-origin data.
因此,它不想读取数据,因为您的图像可能是恶意的。为了防止这种情况,可以将图像托管在您的服务器上,或者执行诸如 Base64 之类的操作,对您想要的图像进行编码并将其嵌入页面中。
可以看到base64编码的例子here ,您可以在互联网上找到 Base64 编码器。
关于Javascript - fillRect和drawImage之后的getImageData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15502999/