如何在HTML5中调色图像 [英] How to tint an image in HTML5

查看:338
本文介绍了如何在HTML5中调色图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个图像,而不是从原点减去颜色,我想添加它们。有没有一个快速的方法来做到这一点在HTML5与JavaScript?

解决方案

是的有两种简单的方法可以使用。 p>

方法1 - 复合模式



复合模式 lighter



您可以使用单行代码激活它(



结论



当然,复合模式更多



但是你可以使用第二种方法来复合模式不支持(例如它有一个暗模式最初 - 这是从规范中删除的xor模式只适用于alpha位,而不是实际的像素等)。



此外,如果你特别是在添加模式之后,您可以始终通过将其颜色的alpha值设置为 0.5 ,或使用 globalAlpha 为您在顶部绘制图像的情况下设置任何下一个绘制的Alpha值。这将调暗内容,并作为一个乘法模式(在结束时减少)。


I want to tint an Image but instead of subtracting colors from the origin, I want to add them. Is there a quick way to do this in HTML5 with javascript?

解决方案

Yes there are two simple ways you can use.

Method 1 - Composite mode

The composite mode lighter is in reality an additive mode.

You can activate it with a single line of code (online demo here):

ctx.globalCompositeOperation = 'lighter';

The next thing drawn will add to what is in the background which gives you this result if you painted half the image with a sepia toned rectangle.

Method 2 - manual manipulation of buffer

The other way is to manipulate the buffer itself with a few steps - this is basically the the exact same as the lighter mode but done the "low level" way.

This of course, as basis, gives you a multitude of other possibilities with manipulating the image data (multiplication, subtract, negate, solarize, convolutions etc.):

/// get the pixel data for current content
buffer = ctx.getImageData(0, 0, wh, h);

/// the color for addition
c = {r:0, g: 127, b: 200};

/// loop through pixel array (RGBA = 4 bytes)
for(; i < len; i += 4) {
    data[i]     = data[i]     + c.r;  /// add R
    data[i + 1] = data[i + 1] + c.g;  /// add G
    data[i + 2] = data[i + 2] + c.b;  /// add B
}

/// we're done, put back the new data to canvas
ctx.putImageData(buffer, 0, 0);

Which results in this:

Not that hard! Please notice that we don't need to clamp the values as this array buffer type will do this for us (the array the canvas is using is of type Uint8ClampedArray).

Here is an online demo for this approach.

Conclusion

Of course, the composite mode is more (actual) low-level and performs therefor better than iterating the buffer using JavaScript.

But you can use the second method for things composite mode does not support (e.g. it had a darken mode initially - this is however removed from the specs. The xor mode works only on alpha bits, not the actual pixels and so forth).

In addition - if you're not particularly after additive mode you can always draw next shape on top either by setting its color's alpha value to 0.5, or use globalAlpha to set alpha value for any next draw in cases where you have an image drawn on top. This will tint the content and behave as a multiply mode (with a reduction at the end).

这篇关于如何在HTML5中调色图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆