javascript - html5 Canvas 填充文本具有特定的 alpha 和背景具有不同的 alpha

标签 javascript html canvas globalcompositeoperation

我正在尝试将文本绘制到具有特定 Alpha 级别的 Canvas 上,并剪辑文本并使用其自己的 Alpha 级别绘制背景颜色:

ctx.globalCompositeOperation = '...';
    ctx.fillStyle = 'rgba(' + fgcolor.r + ', ' +  fgcolor.g + ', ' + fgcolor.b + ',' + (fgcolor.a / 255.0) + ')';
       ctx.fillText(String.fromCharCode(chr), x,y);
ctx.globalCompositeOperation = '...';
    ctx.fillStyle = 'rgba(' + bgcolor.r + ', ' +  bgcolor.g + ', ' + bgcolor.b + ',' + (bgcolor.a / 255.0) + ')';
    ctx.fillRect(x, y, chr_width, chr_height);

我尝试使用 globalCompositeOperation 和 beginPath 但无法达到预期的结果。我还想避免使用drawImage和离屏 Canvas ,因为速度是一个主要问题。

最佳答案

此函数会将 RGBA 颜色转换为 RGB:

function RGBAtoRGB(r, g, b, a, backgroundR,backgroundG,backgroundB){
  var r3 = Math.round(((1 - a) * backgroundR) + (a * r))
  var g3 = Math.round(((1 - a) * backgroundG) + (a * g))
  var b3 = Math.round(((1 - a) * backgroundB) + (a * b))
  return "rgb("+r3+","+g3+","+b3+")";
}  
  1. 将背景RGBA转换为RGB并用RGB填充背景。

  2. 将前景 RGBA 转换为 RGB,并用 RGB 填充前景文本。

关于javascript - html5 Canvas 填充文本具有特定的 alpha 和背景具有不同的 alpha,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29108950/

相关文章:

Javascript reduce 不断返回 undefined

html - 如何禁用内容变小?

Javascript Canvas 刷新闪烁

javascript - 如何停止 easljs 中的事件气泡?

java - 如何在 Canvas 中自由移动?

javascript - 如何在 promise 链中间成功循环

javascript - 由于参数不执行,因此使用其他选择器重新选择选择器

javascript - 即使没有人使用它,也会在一定的时间重新加载网页

html - Aframe Sphere-Collider 碰撞触发功能

html - 如何使用 HTML5 Canvas 绘制 donut 的一部分?