我有一个png图像,我想转换成灰度级.我设法将其转换为灰度,但它也会改变图像透明度的颜色.如何在不改变图像的透明区域的情况下更改其颜色?
var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var img = new Image(); img.src = 'image.png'; ctx.drawImage(img,0); var imageData = ctx.getImageData(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);
解决方法
阿尔法是“不是一种颜色”.您应该将其原样复制,使透明部分透明.只需删除行:
px[i+3] = greyScale;