简体   繁体   中英

change color of image to greyscale in html5

I have a png image which I want to convert into grey scale. I managed to convert it into greyscale however it also changes the color for transparent ares of the image. How can I change its color without changing the transparent area of the image?

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);

Alpha is "not a color". You should copy it as it is, leaving the transparent part transparent. Just remove the line:

px[i+3] = greyScale;

I am not fully sure about purpose of this, but since the question is also tagged "HTML5" I assume it might be needed for purposes different than eg image manipulation library. If that's not some kind of an image editor or HTML5 game, and you just need to convert some of your images to grayscale eg on hover, you may as well use CSS:

.grayscale {
    filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale"); /* Firefox 10+, Firefox on Android */
    filter: gray; /* IE6-9 */
    -webkit-filter: grayscale(100%); /* Chrome 19+, Safari 6+, Safari 6+ iOS */
}

If that's not suitable, please post more information about why do you need to do this

这个插件(tancolor.js)做了你想要实现的类似的事情,你可以尝试检查源代码,并且有一个可以让你测试的东西。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM