我有一個問題:從圖像中讀取像素的RGBA數據。但是我面對的是所有RGBA數據(所有像素都是4個字節)零值。 我使用此JavaScript的代碼:通過JavaScript思考閱讀像素數據Canvas
順便說一下,我使用此代碼的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() {
\t \t 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() {
\t
// 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>
\t <title>Image processing</title>
\t <style type="text/css">
\t
</style>
</head>
<body>
<canvas id="mycanvas" width="300" height="227">
\t
</canvas>
<img src="https://mdn.mozillademos.org/files/5397/rhino.jpg" id="image" style="display:none;">
\t
</style>
\t
</style>="">
<script src="img.js">
</script>
\t
</body>
</html>
的可能的複製[CanvasContext2D的drawImage()問題\ [onload和CORS \]](https://stackoverflow.com/questions/32880641/canvascontext2d-drawimage-issue-onload-and-cors) – Kaiido
你必須等你的圖像加載之前,已經繪製在c anvas在檢索其imageData之前。 這裏你調用'onload'處理程序中的getImageData,這意味着它在'img.src =「...之後被調用。 img.crossOrigin =「...」;'搜索「異步+ javascript」。 – Kaiido