[Javascript] 製作 div 的反差色,解決上面文字顏色的問題

2023-10-17

最近在處理一些前端的東西,遇到一個問題,就是假設設計在一個 <div> 有 background-image 是可以讓客戶更換的

但是,在這 <div>  上面有文字,文字有顏色,如果可以設定一張純白,純嘿,或是花花綠綠的圖該怎麼辦 ?



1. 讓客戶自訂文字顏色,我想這是大部分會用的方法,簡單粗暴,在後台設定直接讓客戶選擇文字顏色,但是通常客戶是麻瓜

2.善用遮罩,在文字跟 <div> 中間再加上一層底色,這樣凸顯文字,就可以不用管圖片,而且有質感,我想大部分會用這種解法,從設計去解決問題


3. 今天提供第三種作法,但是,這也不是完美,但是堪用,如果條件許可,就用前兩個方法,首先我找到一個  js 的  套件 - background-color-theif

他主要目的,就是可以將一張圖片,在前端概算出他的顏色



程式碼也很簡單,但是因為我是在 div 裡面的 image 所以這時候我範例就是得生出一個 img 的 element 然後,並將 src 設定成該 div 的 backround-image 

在送入這 library ,之後回拿到一個顏色,此時將 要顯示的文字顯示成 該顏色,在使用 CSS  filter:invert(100%) 就可以了,


Source Code:

&lt;script src=&quot;background-color-theif.js&quot;&gt;&lt;/script&gt; &lt;div style=&quot;background-image: url(sample1.jpg); text-align: center; background-repeat: no-repeat; background-size: contain; width: 34%; height: 500px; padding-top: 200px; &quot; id=&quot;div1&quot;&gt; &lt;span style=&quot;font-size: 50px&quot; id=&quot;span1&quot;&gt;測試1&lt;/span&gt; &lt;/div&gt; &lt;script&gt; const rgbToHex = (rgb) =&gt; &#39;#&#39; + [rgb[0], rgb[1], rgb[2]].map(x =&gt; { const hex = x.toString(16) return hex.length === 1 ? &#39;0&#39; + hex : hex }).join(&#39;&#39;) var backgroundColorThief = new BackgroundColorTheif(); //將 div 的圖片偷出來&#65292;然後製作一個不再畫面上的圖片 var imgEl1 = $(&#39;&lt;img&gt;&#39;); imgEl1.attr(&#39;src&#39;, $(&#39;#div1&#39;).css(&#39;background-image&#39;).replace(&#39;url(&#39;, &#39;&#39;).replace(&#39;)&#39;, &#39;&#39;).replace(/\&quot;/gi, &quot;&quot;)); //Call backgroundColorThief lib 取得 大概的顏色判斷 var rgb1 = backgroundColorThief.getBackGroundColor((imgEl1).get(0)); //將顏色設定成該顏色 $(&#39;#span1&#39;).css(&#39;color&#39;, rgbToHex(rgb1)); //執行顏色反差 $(&#39;#span1&#39;).css(&#39;filter&#39;, &#39;invert(100%)&#39;); &lt;/script&gt;


Result:


這邊做了一些實驗,因為他是概算,所以在一些時候可能會成立,但是如果你的顏色真的是五顏六色,可能還是會不準像是測試圖片中的測試2一樣


reference:
https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb

https://github.com/SodhanaLibrary/Background-Color-Thief



當麻許的碎念筆記 2014 | Donma Hsu Design.