html5 – context.getImageData()操作不安全

前端之家收集整理的这篇文章主要介绍了html5 – context.getImageData()操作不安全前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想为 HTML5画布实现一个简单的灰度过滤器,但我可以将Image数据作为像素抓取.我从FF和Chrome获得安全警告.最后,滤镜不会使图像变灰.

JS FIDLE CODE

JS:

var canvas = document.getElementById('canvas');       
var context = canvas.getContext('2d');  

var image = new Image();
image.onload = function () {
  if (image.width != canvas.width)
    canvas.width = image.width;
  if (image.height != canvas.height)
    canvas.height = image.height;
  context.clearRect(0,canvas.width,canvas.height);
  context.drawImage(image,canvas.height);
  var imageData = context.getImageData(0,canvas.height);
  filter(imageData);
  context.putImageData(imageData,0);
}
image.src = "http://i0.gmx.net/images/302/17520302,pd=2,h=192,mxh=600,mxw=800,w=300.jpg";

function filter(imageData){
 var d = imageData.data;
   for (var i = 0; i < d.length; i += 4) {
     var r = d[i];
     var g = d[i + 1];
     var b = d[i + 2];
     d[i] = d[i + 1] = d[i + 2] = (r+g+b)/3;
   }
return imageData;
}

解决方法

这是一项安全功能.从 W3开始:

The getImageData(sx,sy,sw,sh) method must,if the canvas element’s origin-clean flag is set to false,throw a SecurityError exception

这是为了防止恶意网站所有者将用户浏览器可访问的潜在私有图像加载到画布上,然后将数据发送到自己的服务器.如果出现以下情况,可以关闭原点清洁:

  • The element’s 2D context’s drawImage() method is called with an HTMLImageElement or an HTMLVideoElement whose origin is not the same
    as that of the Document object that owns the canvas element.

  • The element’s 2D context’s drawImage() method is called with an HTMLCanvasElement whose origin-clean flag is false.

  • The element’s 2D context’s fillStyle attribute is set to a CanvasPattern object that was created from an HTMLImageElement or an
    HTMLVideoElement whose origin was not the same as that of the Document
    object that owns the canvas element when the pattern was created.

  • The element’s 2D context’s fillStyle attribute is set to a CanvasPattern object that was created from an HTMLCanvasElement whose
    origin-clean flag was false when the pattern was created.

  • The element’s 2D context’s strokeStyle attribute is set to a CanvasPattern object that was created from an HTMLImageElement or an
    HTMLVideoElement whose origin was not the same as that of the Document
    object that owns the canvas element when the pattern was created.

  • The element’s 2D context’s strokeStyle attribute is set to a CanvasPattern object that was created from an HTMLCanvasElement whose
    origin-clean flag was false when the pattern was created.

  • The element’s 2D context’s fillText() or strokeText() methods are invoked and end up using a font that has an origin that is not the
    same as that of the Document object that owns the canvas element.

07001

猜你在找的HTML5相关文章