[CSS] 混合模式應用-產品動態選色

Ally Zeng
[AZ] 下筆記。
Published in
7 min readNov 21, 2019

blend-mode

<blend-mode>
CSS混和模式採用前景和背景色, 將混合層中的每個重疊像素執行混合模式計算,並返回像素最終的顏色值。

混合模式 <blend-mode>

簡單來說,就是讓 CSS 能夠實現如同在 Photoshop 中使用混合模式的效果。

▎語法

<blend-mode> = normal | multiply | screen | overlay | darken | lighten | color-dodge | color-burn | hard-light | soft-light | difference | exclusion | hue | saturation | color | luminositymix-blend-mode: normal;
background-blend-mode: multiply;

# 屬性

mix-blend-mode
如同 Photoshop 中的圖層混合模式,元素會與有重疊的父層元素內容及背景混和。

background-blend-mode
背景混合模式, 混和對象為元素的背景圖片以及背景色。

應用

接下來我們要利用mix-blend-mode結合SVG來做一個產品動態選色的範例,該範例來自 codrops文章,以下是我自己的實作筆記,希望對你有所幫助,開始吧~

01/ 準備產品圖

準備一張產品為白底的圖片,如下圖T卹依據各自的需求當然也可以是沙發或牆面等,但注意底色必須為白色,最終我們會替換衣服白色的部分。

圖片來源:Alex Holyoake / Unsplash

02/ 繪製產品的向量路徑

以下是用 Adobe Illustrator 來繪製向量,如果沒有這個軟體可以用免費的線上軟體 Method Draw 來替代。

建立與照片相同尺寸(1920 x 1280像素)的畫布: 檔案 〉新增。

1920 x 1280

將照片置中,並在圖層面板中鎖定,我們要防止繪製路徑時不小心將圖片移動或變形。

在圖片上方新增一個空白圖層,點擊鋼筆工具,將照片盡可能放大以供描繪T卹的細節。

完成描繪後,你可以選擇對路徑填充任何顏色觀看結果,這個色塊就是我們將要在網頁中替換產品顏色的部分。

接著關閉或刪除下方圖片,保持路徑周圍的空白,空白部分就是我們在網頁中放置產品底圖的區域。

03/ 匯出及優化SVG

匯出SVG:檔案 〉轉存 〉轉為螢幕適用 (或 Ctrl+Alt+E )。

用編輯器開啟匯出的SVG文件並複製內容。

開啟 SVGOMG 來優化:
點擊側選單 Paste Markup〉貼上剛剛複製的內容 ( Ctrl+ V ) 〉切換至 MARKUP 頁籤 〉複製SVG。原本我們的SVG中有兩條路徑,現在被合併為一條了。

好了前置工作完畢,現在在 CodePen 創建一個新的 Pen。

04/ 建立框架

創建一個<div>容器,
在其中貼上剛剛複製好的 SVG,分別給<svg>及<path>命名一個 ID,
接下來,在 SVG 的下方加上產品圖<img>,就是步驟1中所準備的圖片,也給它一個ID。

<div id="demo">
<svg id="product-svg" xmlns="..." viewbox="0 0 1920 1280">
<path id="product-shape" fill='#EDB366' d="..." />
</svg>
<img id="product-image" src="..." />
</div>

在容器的下方加上一個選色器:

<input class="jscolor {onFineChange:'changeColor(this)'}" value="EDB366">

05/ SVG 的 CSS 概念

我們需要用 CSS 將 SVG 浮動固定在圖片之上層,可以想像就是整張圖片上蓋了一層透明的膜,但是在T卹處的區塊有顏色覆蓋,而這個被重疊的色塊 <path>就是最終我們要用到混和模式 mix-blend-mode 的地方。

// sass
#demo
position: relative
z-index: 1
margin: 0 auto
width: 60vw
#product-svg
position: absolute
top: 0
left: 0
z-index: 2
width: 100%
height: 100%
mix-blend-mode: multiply
// mix-blend-mode: multiply
// mix-blend-mode: screen
// mix-blend-mode: overlay
// mix-blend-mode: darken
// mix-blend-mode: lighten
// mix-blend-mode: color-dodge
// mix-blend-mode: color-burn
// mix-blend-mode: hard-light
// mix-blend-mode: soft-light
// mix-blend-mode: difference
// mix-blend-mode: exclusion
// mix-blend-mode: hue
// mix-blend-mode: saturation
// mix-blend-mode: color
// mix-blend-mode: luminosity
#product-image
width: 100%
display: block

06/ 即時更改顏色

選色器:套件 jscolor

<input class="jscolor {onFineChange:'changeColor(this)'}" value="EDB366">

選色紐:

<button style="background-color:#728472" value="#728472"></button>

最後,我們要在點擊選色器(或選色紐)時取得色碼,並且套用在混和模式的色塊上, 這裡只需兩三行 JavaScript 很簡單就可以完成!

直接去看看~ 👇👇👇

▎範例

▎支援度

目前主流的瀏覽器大多已支持,除了 IE。

但要注意的是,如果在 SVG 上使用混和模式就不是那麼樂觀了...

--

--