使用Canvas操作像素的方法

2020-04-21 07:43:37易采站长站整理

.then(initCamera)
.catch(console.error)
);
}

Live Demo

效果

到目前为止,我们所介绍的所有内容都是我们需要的基础,以便为视频或图像创建不同的效果。我们可以通过独立转换每种颜色来使用很多不同的效果。

灰阶

将颜色转换为灰度可以使用不同的公式/技巧以不同的方式完成,以避免陷入太深的问题我将向您展示基于GIMP desaturate tool去饱和工具和Luma的五个公式:


Gray = 0.21R + 0.72G + 0.07B // Luminosity
Gray = (R + G + B) ÷ 3 // Average Brightness
Gray = 0.299R + 0.587G + 0.114B // rec601 standard
Gray = 0.2126R + 0.7152G + 0.0722B // ITU-R BT.709 standard
Gray = 0.2627R + 0.6780G + 0.0593B // ITU-R BT.2100 standard

我们想要使用这些公式找到的是每个像素颜色的亮度等级。该值的范围从0(黑色)到255(白色)。这些值将创建灰度(黑白)效果。

这意味着最亮的颜色将最接近255,最暗的颜色最接近0。

Live Demo

双色调

双色调效果和灰度效果的区别在于使用了两种颜色。在灰度上,您有一个从黑色到白色的渐变色,而在双色调中,您可以从任何颜色到任何其他颜色(从蓝色到粉红色)都有一个渐变。

使用灰度的强度值,我们可以将其替换为梯度值。

我们需要创建一个从ColorA到ColorB的渐变。


function createGradient(colorA, colorB) {
// Values of the gradient from colorA to colorB
var gradient = [];
// the maximum color value is 255
var maxValue = 255;
// Convert the hex color values to RGB object
var from = getRGBColor(colorA);
var to = getRGBColor(colorB);

// Creates 256 colors from Color A to Color B
for (var i = 0; i <= maxValue; i++) {
// IntensityB will go from 0 to 255
// IntensityA will go from 255 to 0
// IntensityA will decrease intensity while instensityB will increase
// What this means is that ColorA will start solid and slowly transform into ColorB
// If you look at it in other way the transparency of color A will increase and the transparency of color B will decrease
var intensityB = i;
var intensityA = maxValue - intensityB;

// The formula below combines the two color based on their intensity
// (IntensityA * ColorA + IntensityB * ColorB) / maxValue
gradient[i] = {
r: (intensityA*from.r + intensityB*to.r) / maxValue,
g: (intensityA*from.g + intensityB*to.g) / maxValue,
b: (intensityA*from.b + intensityB*to.b) / maxValue
};
}

return gradient;
}

// Helper function to convert 6digit hex values to a RGB color object
function getRGBColor(hex)
{
var colorValue;

if (hex[0] === '#') {
hex = hex.substr(1);
}