haoqi.design
THEME[A]SOUND[|]
--:--GMT+8 CN --:--0001 X 0001 Y

Wasm design utils

May 31, 2026

2025

@wenhaoqi/wasm_design_utils 是一组浏览器端设计小工具:sRGB ↔ OKLCH 色彩转换、图片取色、以及 squircle / capsule 的 SVG 路径生成。npm:@wenhaoqi/wasm_design_utils。

它最初是在做 Reunimos™ 时沉淀下来的,后来打包开源。

#安装

Bash
1npm install @wenhaoqi/wasm_design_utils

包是 ESM,WASM 默认内联在包里,一般不用自己托管 .wasm 文件。

所有 API 都是 async,调用时要 await。

#三个模块,按需引入

  • @wenhaoqi/wasm_design_utils/color — RGB ↔ OKLCH
  • @wenhaoqi/wasm_design_utils/extract-colors — 从图片提取主色
  • @wenhaoqi/wasm_design_utils/squircle — 生成平滑圆角 SVG path

也可以从根路径 @wenhaoqi/wasm_design_utils 一次性导入全部 API。

#颜色

JavaScript
1import { rgb2oklch, oklch2rgb_abs, oklch2rgb_rel } from "@wenhaoqi/wasm_design_utils/color";
2
3// sRGB 0–255 → OKLCH
4const { L, C, h } = await rgb2oklch(128, 100, 231);
5
6// OKLCH → sRGB,直接指定色度
7const { R, G, B } = await oklch2rgb_abs(L, C, h);
8
9// 只定明暗和色相,彩度用 0–1 滑杆(更直觉)
10const tint = await oklch2rgb_rel(L, h, 0.5);

init() 可选。不传的话,第一次调用转换函数时会自动加载 WASM;想在页面启动时预热,可以提前 await init()。

#取色

JavaScript
1import extractColors from "@wenhaoqi/wasm_design_utils/extract-colors";
2
3// 从 <img> 提取调色板,第一个色块通常是主色
4const [dominant, ...rest] = await extractColors(img);
5
6// 常用参数
7const palette = await extractColors(img, {
8 pixels: 64000, // 抽样分辨率,默认 64000
9 distance: 0.22, // 聚类距离
10 crossOrigin: "anonymous", // 跨域图片 URL 时需要
11});

input 支持:图片 URL 字符串、<img> / Image、ImageData。

#平滑圆角

普通 border-radius 在大圆角时转角容易发尖;squircle 用 SVG path 过渡更顺。

JavaScript
1import { getPath } from "@wenhaoqi/wasm_design_utils/squircle";
2
3const d = await getPath("squircle", 200, 120, 16);
4pathEl.setAttribute("d", d);
5// viewBox 对应:0 0 200 120

shape 也可以是 "capsule"(胶囊形标签、Chip 等)。

#本站怎么用

文章页图片放大时,会用取色 + OKLCH 生成跟图片主色接近的蒙层背景:

  1. extractColors 取主色
  2. rgb2oklch 转成 OKLCH
  3. 按明暗主题调整亮度,再 oklch2rgb_abs 转回 RGB

这样全屏查看图片时,背景不会突兀地跳成纯黑。

#Next.js 注意

需要在客户端使用(依赖 Image 和 WebAssembly)。放在 "use client" 组件里,或用动态 import() 加载即可。

Metadata
Last Updated
May 31, 2026
Dimensions
1×1
Characters
—
Links
Home
Twitter/XGitHubFigma