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