颜色
语法
RESOURCE.Colors
返回值
[]images.Color
Resources.Colors
方法返回图像中最主要的颜色切片,从最主要到最不主要排序。此方法速度很快,但如果也缩小图像,则可以通过从缩放的图像中提取颜色来提高性能。
方法
每种颜色都是一个对象,具有以下方法
- ColorHex
- v0.125.0 中的新增功能
- (
string
)返回十六进制颜色值,前缀为井号。 - 亮度
- v0.125.0 中的新增功能
- (
float64
)返回 sRGB 色彩空间中颜色的相对亮度,范围为 [0, 1]。值0
表示最深的黑色,而值1
表示最亮的白色。
排序
作为一个虚构的示例,创建一个图像的主要颜色表,其中最主要的颜色排在第一位,并显示每种主要颜色的相对亮度
{{ with resources.Get "images/a.jpg" }}
<table>
<thead>
<tr>
<th>Color</th>
<th>Relative luminance</th>
</tr>
</thead>
<tbody>
{{ range .Colors }}
<tr>
<td>{{ .ColorHex }}</td>
<td>{{ .Luminance | lang.FormatNumber 4 }}</td>
</tr>
{{ end }}
</tbody>
</table>
{{ end }}
Hugo 将其渲染为
ColorHex | 相对亮度 |
---|---|
#bebebd |
0.5145 |
#514947 |
0.0697 |
#768a9a |
0.2436 |
#647789 |
0.1771 |
#90725e |
0.1877 |
#a48974 |
0.2704 |
要按主要程度排序,最不主要的颜色排在第一位
{{ range .Colors | collections.Reverse }}
要按相对亮度排序,最暗的颜色排在第一位
{{ range sort .Colors "Luminance" }}
要按相对亮度排序,最亮的颜色排在第一位,请使用以下任一构造
{{ range sort .Colors "Luminance" | collections.Reverse }}
{{ range sort .Colors "Luminance" "desc" }}
示例
图像边框
要使用最主要的颜色为图像添加 5 像素边框
{{ with resources.Get "images/a.jpg" }}
{{ $mostDominant := index .Colors 0 }}
{{ $filter := images.Padding 5 $mostDominant }}
{{ with .Filter $filter }}
<img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
{{ end }}
{{ end }}
要使用最暗的主要颜色为图像添加 5 像素边框
{{ with resources.Get "images/a.jpg" }}
{{ $darkest := index (sort .Colors "Luminance") 0 }}
{{ $filter := images.Padding 5 $darkest }}
{{ with .Filter $filter }}
<img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
{{ end }}
{{ end }}
深色背景上的浅色文本
要创建一个文本框,其中前景和背景颜色来源于图像最亮和最暗的主要颜色
{{ with resources.Get "images/a.jpg" }}
{{ $darkest := index (sort .Colors "Luminance") 0 }}
{{ $lightest := index (sort .Colors "Luminance" "desc") 0 }}
<div style="background: {{ $darkest }};">
<div style="color: {{ $lightest }};">
<p>This is light text on a dark background.</p>
</div>
</div>
{{ end }}
WCAG 对比度
在前面的示例中,我们将浅色文本放在深色背景上,但是这种颜色组合是否符合 WCAG 中对最小或增强对比度的指导原则?
WCAG 将对比度定义为
$$contrast\ ratio = { L_1 + 0.05 \over L_2 + 0.05 }$$其中,$L_1$ 是最亮颜色的相对亮度,$L_2$ 是最暗颜色的相对亮度。
计算对比度以确定 WCAG 合规性
{{ with resources.Get "images/a.jpg" }}
{{ $lightest := index (sort .Colors "Luminance" "desc") 0 }}
{{ $darkest := index (sort .Colors "Luminance") 0 }}
{{ $cr := div
(add $lightest.Luminance 0.05)
(add $darkest.Luminance 0.05)
}}
{{ if ge $cr 7.5 }}
{{ printf "The %.2f contrast ratio conforms to WCAG Level AAA." $cr }}
{{ else if ge $cr 4.5 }}
{{ printf "The %.2f contrast ratio conforms to WCAG Level AA." $cr }}
{{ else }}
{{ printf "The %.2f contrast ratio does not conform to WCAG guidelines." $cr }}
{{ end }}
{{ end }}