非服务器模式下运行getImageData函数出现 the operation is insecure
作者:互联网
我在非服务器模式下运行了一个获取图片像素数据的函数。报错。
报错为the operation is insecure.
解决思路为:打开服务器,将运行由:file:///D:/wamp64/www/js_programme/canvas_pixel.html
改为:http://localhost/js_programme/canvas_pixel.html
问题解决,结果图片:
下面放上自己的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas-像素操作</title>
</head>
<body>
<canvas id="canvas" width="300" height="227"></canvas>
<canvas id="canvas2" width="300" height="200"></canvas>
<canvas id="canvas3" width="300" height="200"></canvas>
</body>
<script>
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var img=new Image();// 创建一个<img>元素
img.crossOrigin='anonymous';
img.src='./rhino.jpg';
img.onload=function(){
ctx.drawImage(img,0,0);
img.style.display='none';
};
canvas.addEventListener('click',function(e){
var x=e.offsetX;
var y=e.offsetY;
console.log(ctx.getImageData(100,150,5,5));
console.log(ctx.getImageData(x,y,1,1).data);
});
/*
var img=new Image();
img.src='./rhino.jpg';
img.crossOrigin='anonymous';//这行代码不能够要;
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext('2d');
img.οnlοad=function(){
ctx.drawImage(img,0,0);
img.style.display='none';
};
var hoveredColor=document.getElementById('canvas2').getContext('2d');
var selectedColor=document.getElementById('canvas3').getContext('2d');
hoveredColor.rect(0,0,300,200);
selectedColor.rect(0,0,300,200);
function pick(event,destination){
var x=event.layerX;//鼠标的x,y数值;
var y=event.layerY;
console.log('mouse position of x,y is ',x,y);
var imagedata=ctx.getImageData(x,y,2,2).data;
//console.log('pixel is =',pixel);
//var data=pixel.data;
console.log('data is equal to ',imagedata);
const rgba='rgba(data[0],data[1],data[2],data[3]/255})';
destination.style.background=rgba;
destination.textContext=rgba;
return rgba;
}
canvas.addEventListener('mousemove',function(event){
pick(event,hoveredColor);
});
canvas.addEventListener('click',function(event){
pick(event,selectedColor);
});
*/
</script>
</html>
标签:canvas,img,insecure,ctx,getImageData,var,operation,data,event 来源: https://blog.csdn.net/weixin_47024922/article/details/120576180