在这篇文章中,为什么在循环中i
增加了 4 而不是 1?。我试过changong i+=4
to,i++
但它不能正常工作。你能告诉我背后的原因是什么吗?
function grayScale(context, canvas) {
var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
var pixels = imgData.data;
for (var i = 0, n = pixels.length; i < n; i += 4) {
var grayscale = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
pixels[i ] = grayscale; // red
pixels[i+1] = grayscale; // green
pixels[i+2] = grayscale; // blue
//pixels[i+3] is alpha
}
//redraw the image in black & white
context.putImageData(imgData, 0, 0);
}
//add the function call in the imageObj.onload
imageObj.onload = function(){
context.drawImage(imageObj, destX, destY);
grayScale(context, canvas);
};