我找不到這裏的bug。我不知道我錯過了哪些東西,而不是讓我的代碼將圖像轉換爲灰度。如果有人可以嘗試這些代碼並幫助我找出問題,那將會很有幫助。嗨,有人可以幫助在html5灰度轉換代碼?
<!doctype html>
<html>
<head>
<title>Canvas API</title>
</head>
<body>
<!-- In order to have canvas we need to use the canvas tag -->
<canvas id="c" width="500" height="500"></canvas>
<!-- To use canvas we need to access is from javascript code -->
<script>
var c = document.querySelector("#c"); // grab a canvas with id="c"
var ctx = c.getContext("2d"); // context in which we are using it
var img = new Image();
img.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg';
img.onload = function() {
ctx.drawImage(img, 0, 0);
img.style.display = 'none';
};
var myData = ctx.getImageData(0,0, 500, 500);
console.log(myData);
var grayscale = function(imageData) {
var numPixels = imageData.data.length;
for (var i = 0; i < numPixels; i+=4) {
var avg = 0.34 * imageData.data[i] + 0.5 * imageData.data[i + 1] + 0.16 * imageData.data[i + 2];
imageData.data[i*4+0] = avg;
imageData.data[i*4+1] = avg;
imageData.data[i*4+2] = avg;
// imageData.data[i*4+3] = 255;
}
ctx.putImageData(imageData, 0, 0);
};
grayscale(myData);
</script>
</body>
</html>
你有沒有調試過你的代碼,找出具體的問題在哪裏? – PeeHaa
在嘗試修改畫布,將數據獲取和灰度移動到加載回調之前,這看起來像圖像可能尚未加載 –