html设置图像灰度,在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?

我有一个png图像,我想把它转换成灰度。我设法将它转换成灰度,但是它也改变了图像透明ares的颜色。如何改变它的颜色而不改变图像的透明区域?

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

3 个解决方案

#1

9

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;

#2

1

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 e.g. 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 e.g. on hover, you may as well use CSS:

我不完全确定这个问题的目的,但是由于这个问题也被标记为“HTML5”,所以我认为它可能需要用于与图像处理库不同的目的。如果这不是某种图像编辑器或HTML5游戏,你只需要将一些图像转换为灰度,例如在鼠标悬停时,你也可以使用CSS:

.grayscale {

filter: url("data:image/svg+xml;utf8,#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

如果这是不合适的,请提供更多关于为什么你需要这样做的信息。

#3

0

this plugin (tancolor.js) does the similar thing that you want to achieve, you can try to check the source code and there's an intractive demo for you to test things out.

这个插件(tancolor.js)做了类似的事情,你可以试着检查源代码,并且有一个内部的demo来测试。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值