我有一个 png 图像,我想将其转换为灰度。我设法将其转换为灰度,但它也改变了图像透明区域的颜色。如何在不更改图像透明区域的情况下更改其颜色?
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = 'image.png';
ctx.drawImage(img, 0, 0);
var imageData = ctx.getImageData(0, 0, 420, 420);
var px = imageData.data;
var len = px.length;
for (var i = 0; i < len; i+=4) {
var redPx = px[i];
var greenPx = px[i+1];
var bluePx = px[i+2];
var alphaPx = px[i+3];
var greyScale = redPx * .3 + greenPx * .59 + bluePx * .11;
px[i] = greyScale;
px[i+1] = greyScale;
px[i+2] = greyScale;
px[i+3] = greyScale;
}
ctx.putImageData(imageData, 0, 0);