javascript - 使用 HTML Canvas 以红色和黑白颜色渲染视频

标签 javascript html css image canvas

我需要用红色的 HTML Canvas 渲染视频。下面的代码(如果不起作用,请在此处尝试 codepen code )。此代码添加红色层,但我首先需要 - 去饱和,降低亮度后才添加红色层。我尝试使用像素(性能问题),ctx.filter 也不起作用。

enter image description here enter image description here

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/

相关文章:

jquery addclass 不适用于 animate.css

html - 如何使用 CSS 为居中列的相邻空间着色?

javascript - 使用 javascript 将多个过滤器类别应用于 <li>(s) 列表

html - 水平导航子菜单对齐 CSS

css - 如何只打印页面的特定部分?

JavaScript:检测 CSS3 动画何时结束

javascript - 如何使用Javascript在函数内部调用外部库的函数?

javascript - 在运行时加载 BingMaps API

javascript - 如何在一个div上添加2张图片

javascript - FabricJS 在事件对象/选择周围渲染阴影?