简体   繁体   English

在html5中将图像颜色更改为灰度

[英]change color of image to greyscale in html5

I have a png image which I want to convert into grey scale. 我有一个png图像,我想将其转换为灰度。 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. 我不完全确定这个目的,但由于问题也标记为“HTML5”,我认为可能需要与图像处理库不同的目的。 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: 如果那不是某种图像编辑器或HTML5游戏,你只需要将一些图像转换为灰度,例如悬停,你也可以使用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)做了你想要实现的类似的事情,你可以尝试检查源代码,并且有一个可以让你测试的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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