css - 如何将图像颜色置于文本下方?

标签 css html image image-processing canvas

使文本颜色根据其在相应图像文件中的适当位置采用颜色的最佳方法是什么?此外,有些文本有些部分是一种颜色,有些部分是其他颜色,因此看起来很平滑。

Twitter Data 做到了这一点,其中的文本都是提到 Prince 的推文。

最佳答案

这叫做 compositing .

通过 canvas2d API,它很容易管理:

globalCompositeOperation属性提供了相当广泛的不同合成模式列表。

var img = new Image();
img.onload = function(){
canvas.width = this.width;
canvas.height = this.height;

var ctx = canvas.getContext('2d');
ctx.font = '8px sans-serif';

for(var i=0; i<300; i++){ // fill some dummy text
  let txt = 'Lorem ipsum dolor sit amer '.repeat(20).substring(~~(Math.random()*27));
  ctx.fillText(txt, 0, 7*i)
  }
// at this moment our canvas only has pixels where text is filled.
// 'source-atop' will place new pixels only where there already were pixels
ctx.globalCompositeOperation = 'source-atop';
ctx.drawImage(img, 0,0);
}
img.src = 'https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg';
<canvas id="canvas" width="500" height="300"></canvas>

请注意,对于文本,这也可以在现代浏览器中仅使用 CSS 来实现,这要归功于 background-clip: text;属性:

text.textContent = 'Lorem ipsum dolor sit amer '.repeat(2000);
#text{
  background-image: url(https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg);
  /* pre-fixed (both FF and chrome)*/
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  /* Standards */
  background-clip: text;
  text-fill-color: transparent;
  
  width: 800px;
  height: 1164px;
  line-height: 0.8;
  overflow: hidden;
  text-overflow: hidden;
  font-size: 8px;
  }
<div id="text"></div>

关于css - 如何将图像颜色置于文本下方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45655824/

相关文章:

jquery 对齐到 div 内的底部

javascript - 淡入内容和淡出当前 Div?

javascript - 从表中的 <a> 标记获取 href

javascript - 打开菜单时 mask /覆盖页面

html - 有没有办法像图像大小css一样设置空的div大小

html - 一些背景图片在 iPad 上不显示

jquery "animate"z-index 不工作?

javascript - fa-spin 在启动后停止并重新加载页面

css图像不显示

php - 在 Javascript 中发送动态生成的图像作为 PHP 中的图像标题