阅读 56

canvas读取跨域图片像素失败 Failed to execute getImageData The canvas has been tainted by cross-origin data

错误描述:

Uncaught SecurityError: Failed to execute ‘getImageData’ on ‘CanvasRenderingContext2D’: The canvas has been tainted by cross-origin data.

这个canvas的例子,是读取和操作画布上的像素。该画布将一幅照片显示在画布上,然后试图通过鼠标点击照片,读取点中的像素,并显示在一个div上。

结果报错,如开头所述。错误描述有关键词,跨域,究其原因,是因为展示的这张照片,位于其他站点。

应对之道,将图片的地址加上时间戳,然后再设个跨域属性,可也。

var img = new Image();
var url = 'https://media.prod.mdn.mozit.cloud/attachments/2013/06/22/5397/7a3ec0cae64a95ad454ac3bc2c71c004/rhino.jpg';
img.src = url + '?' + new Date().getTime();
img.setAttribute('crossOrigin', '');
复制代码

完整代码:

<style>
#canvas{
    border:solid 1px #999;
}
#color{
    width:100px;
    height:100px;
}
</style>

<canvas id="canvas" width="310" height="240"></canvas>
<div id="color"></div>

<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var img = new Image();
var url = 'https://media.prod.mdn.mozit.cloud/attachments/2013/06/22/5397/7a3ec0cae64a95ad454ac3bc2c71c004/rhino.jpg';
img.src = url + '?' + new Date().getTime();
img.setAttribute('crossOrigin', '');
img.onload = function() {
  ctx.drawImage(img, 0, 0);
  img.style.display = 'none';
};

var color = document.getElementById('color');

function pick(event) {
  var x = event.layerX;
  var y = event.layerY;
  var pixel = ctx.getImageData(x, y, 1, 1);
  var data = pixel.data;
  var rgba = 'rgba(' + data[0] + ',' + data[1] +
             ',' + data[2] + ',' + (data[3] / 255) + ')';
  color.style.background =  rgba;
  color.textContent = rgba;
}

canvas.addEventListener('mousemove', pick);

</script>
复制代码

结果
在这里插入图片描述

文章分类
代码人生
文章标签