2017-08-12 21 views
0

如何在文字下鋪設圖像顏色?

什麼是使文本顏色根據其在相應的圖像文件中的適當位置的顏色的最佳方式是什麼?此外,一些文字的某些部分是一種顏色,其他部分是其他部分,因此看起來很平滑。

Twitter數據做了這個,其中的文字都是推特提到王子。

回答

1

這就是所謂的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>

+0

真棒,感謝您的示例代碼!這太酷了。 – checks

1

您可以通過mix-blend-mode: difference;輕鬆完成此任務。

.bg { 
 
    background-image: url(https://wallpaperbrowse.com/media/images/html-color-codes-color-tutorials-hero-00e10b1f.jpg); 
 
    background-position: center; 
 
    background-size: cover; 
 
} 
 

 
.el, 
 
.el2, 
 
.el3 { 
 
    padding: 20px; 
 
} 
 

 
.el { 
 
    color: rgb(255, 255, 255); 
 
    mix-blend-mode: difference; 
 
} 
 

 
.el2 { 
 
    color: rgb(255, 0, 0); 
 
    mix-blend-mode: difference; 
 
} 
 

 
.el3 { 
 
    color: rgb(255, 255, 0); 
 
    mix-blend-mode: difference; 
 
}
<div class="wrapper"> 
 
    <div class="bg"> 
 
    <div class="el">directly opposite image color. directly opposite image color. directly opposite image color.</div> 
 
    <div class="el2">one variant. one variant. one variant. one variant. one variant. one variant. one variant.</div> 
 
    <div class="el3">another variant. another variant. another variant. another variant. another variant.</div> 
 
    </div> 
 
</div>

相關問題