通过JavaScript读取像素数据Canvas

时间:2017-06-01 10:15:48

标签: javascript image canvas

我有一个问题是从图像中读取像素的RGBA数据。但我面临所有RGBA数据(所有像素的所有4个字节)零值。 我将此代码用于JavaScript:

顺便说一句,我将此代码用于html。 和tehn我通过Chrome或Firefox运行html但是当我看到控制台日志时,像素数据的所有值都是零。为什么?

var canvas= document.getElementById('mycanvas');
var c=canvas.getContext("2d");

// c.beginPath();
// c.moveTo(0,0);
// c.lineTo(500,200);
// c.stroke();

var img = new Image();   
img.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg'; 
img.crossOrigin = "Anonymous";

// var img= document.getElementById('image')
 img.onload=function () {
		c.drawImage(img,0,0);
 }

var myImageData = c.getImageData(0, 0, 500, 500);
//var myImageData = c.createImageData(600, 600);
var numBytes = myImageData.data.length;
var pixelData=myImageData.data;
console.log (numBytes);
console.log (pixelData);

// var x= function () {
	
// for(var i=0;i<pixelData.length;i+=40)

// {

// pixelData[i]     = 255 - pixelData[i];     // red
//       pixelData[i + 1] = 255 - pixelData[i + 1]; // green
//       pixelData[i + 2] = 255 - pixelData[i + 2]; // blue
//     }
//     c.putImageData(myImageData, 0, 0);
//   };
// //if (pixelData[i]&&pixelData[i+1]&&pixelData[i+2]===255) {

// //console.log (numBytes);

// //} 

// //else {}


// //};

// //
// x();



//pixel = imageData.data[((row * (imageData.width * 4)) + (colume * 4)) + colorindex];

//var img = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");  // here is the most important part because if you dont replace you will get a DOM 18 exception.
//window.location.href=image;
<!DOCTYPE html>
<html>
<head>
	<title>Image processing</title>
	<style type="text/css">
	
</style>
</head>


<body>

<canvas  id="mycanvas"  width="300"  height="227">
	
</canvas>
<img src="https://mdn.mozillademos.org/files/5397/rhino.jpg" id="image" style="display:none;">
	
</style>
	
</style>="">

<script src="img.js">

</script>
	


</body>
</html>

2 个答案:

答案 0 :(得分:0)

由于图像来自另一个域,因此无法正常工作。画布仅接受来自同一原点的图像。您不能也不应该使用不支持 CORS 的外部来源的getImageData()。

但您可以将图像转换为dataURL然后绘制画布。

修改:抱歉没有正确表达。唯一的方法是将图像本地下载到您的服务器/域,然后在画布上绘制。

答案 1 :(得分:0)

我解决了我的问题。

首先作为Mohanesh说我们需要使用Localhost或http域。所以我安装了Python并使用此命令来创建localhost erver。

Python -m http.server

其次我使用了creatpattern命令而不是drawimage.this代码对我有用:

dev environment
var canvas = document.getElementById('mycanvas')
var c = canvas.getContext('2d');
// canvas.height = window.innerHeight;
// canvas.width = window.innerWidth;
var img = document.getElementById("image")
img.crossOrigin = "Anonymous";

var ptrn = c.createPattern(img, 'no-repeat');
c.fillStyle = ptrn;
c.fillRect(0, 0, canvas.width, canvas.height);

var myImageData = c.getImageData(0, 0, canvas.width, canvas.height);
var numBytes = myImageData.data.length;
var pixelData = myImageData.data;
console.log(numBytes);
console.log(pixelData);

相关问题