javascript - HTML5 Canvas |替换颜色 |去除颜色

标签 javascript html image canvas process

创建没有绿色的复制此图像或使绿色透明或从 100X100 px 左上角删除绿色的最快方法是什么

在这种情况下我是否必须检查每个像素值? 这个过程太慢了,例如:对于 100X100px,需要 40000 次循环来检查所有 rgba 值

enter image description here

最佳答案

在支持它的浏览器中,您可以使用 svg 过滤器来做到这一点:

这里是an other Q/A这展示了一种针对固定颜色执行此操作的有趣方法。

这里我做了一个简单的辅助函数,它将为我们设置所需的 tableValues带着一点宽容,我删除了 <feFill>因此所选颜色变得透明( <feFill> 会污染 Chrome 中的 Canvas )。 如果您想替换颜色,您仍然可以使用 Canvas 的合成选项来实现它(下面的代码片段中的注释代码)。

const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = e => {
  canvas.width = img.width;
  canvas.height = img.height;
  // update our filter
  updateChroma([76, 237, 0], 8);
// if you wish to replace the color, uncomment followings
//  ctx.fillStyle = "your_replaceColor";
//  ctx.fillRect(0,0,img.width,img.height);
  ctx.filter = 'url(#chroma)';
  ctx.drawImage(img, 0, 0);
  ctx.filter = 'none';
//  ctx.globalCompositeOperation = 'destination-in';
//  ctx.drawImage(img, 0,0);
};
img.src = "/image/hZm8o.png";

function updateChroma(rgb, tolerance) {
  const sels = ['R', 'G', 'B'];
  rgb.forEach((value, ind) => {
    const fe = document.querySelector('#chroma feFunc' + sels[ind]);
    let vals = '';
    if (!value) {
      vals = '0'
    } else {
      for (let i = 0; i < 256; i++) {
        vals += (Math.abs(value - i) <= tolerance) ? '1 ' : '0 ';
      }
    }
    fe.setAttribute('tableValues', vals);
  });
}
canvas {
  background: ivory
}
<svg width="0" height="0" style="position:absolute;visibility:hidden">
<filter id="chroma" color-interpolation-filters="sRGB"x="0" y="0" height="100%" width="100%">
  <feComponentTransfer>
    <feFuncR type="discrete"/>
    <feFuncG type="discrete"/>
    <feFuncB type="discrete"/>
  </feComponentTransfer>
  <feColorMatrix type="matrix" values="1 0 0 0 0 
                                       0 1 0 0 0
                                       0 0 1 0 0 
                                       1 1 1 1 -1" result="selected"/>
  <feComposite in="SourceGraphic" in2="selected" operator="out"/>
  </filter>
</svg>

<canvas id="canvas"></canvas>

我没有在许多设备上进行广泛的测试,但在启用硬件加速的情况下,这可能比任何像素循环表现更好,因为它应该全部在 GPU 上完成。

<小时/>

但是浏览器支持仍然不是那么好......
所以无论如何你可能需要回退到像素操纵。

在这里,根据您要进行色度处理的对象,您可能需要牺牲一些质量来换取速度。

例如,在视频中,您可以在缩小的 Canvas 上执行色度,然后通过在主 Canvas 上合成来将其拉回,从而在每帧中赢得几次迭代。看这个previous Q/A举个例子。

关于javascript - HTML5 Canvas |替换颜色 |去除颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52713456/

相关文章:

javascript - 如何定位html元素内文本的中心

html - 使用奇数/偶数颜色设置 HTML 样式

html - 溢出 :hidden not working on mobile App

javascript - 建立响应式缩略图画廊

image - JOGL:一些 GL 常量无法解析

Javascript 获取带条件的子字符串

javascript - 如何在 Electron 应用程序中实现 Socket.IO?

javascript - 如何使用 javascript 获取动态加载的 swf 的大小?

可滚动页面上的 Jquery Starfield 插件

java - java中图像的显示和写入