我需要用红色的 HTML Canvas 渲染视频。下面的代码(如果不起作用,请在此处尝试 codepen code )。此代码添加红色层,但我首先需要 - 去饱和,降低亮度后才添加红色层。我尝试使用像素(性能问题),ctx.filter 也不起作用。
const URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
const video = document.createElement('video');
navigator.mediaDevices.getUserMedia({
audio: true,
video: true,
}).then((stream) => {
video.src = URL.createObjectURL(stream);
});
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
const loop = () => {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'rgba(255, 0, 0, .45)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
requestAnimationFrame(loop);
};
loop();
<canvas id="canvas" width="400" height="400"></canvas>
最佳答案
您可以使用multiply
混合模式来剔除其他颜色 channel 。由于您只定义红色,其他 channel 乘以 0,使它们“空”。
请记住在绘制下一个视频帧之前将复合模式重置为“source-over”。
var img = new Image(); img.onload = draw; img.src = "//i.imgur.com/Kzz84cr.png";
function draw() {
c.width = this.width; c.height = this.height;
var ctx = c.getContext("2d");
// main loop
ctx.drawImage(this, 0, 0); // draw video frame
ctx.globalCompositeOperation = "multiply"; // change blending mode
ctx.fillStyle = "red"; // draw red on top
ctx.fillRect(0, 0, c.width, c.height);
ctx.globalCompositeOperation = "source-over"; // "reset"
// rinse, repeat
}
<canvas id=c></canvas>
关于javascript - 使用 HTML Canvas 以红色和黑白颜色渲染视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49308389/