CSS Houdini的Paint API允许通过JavaScript动态绘制背景图像,需先注册worklet模块:CSS.paintWorklet.addModule('my-painter.js');接着在my-painter.js中定义Painter类,实现静态inputProperties指定可配置属性如--circle-color、--circle-size,并编写paint方法利用canvas API绘制图形;然后在CSS中使用background: paint(myBackground)应用自定义背景,结合自定义属性设置样式;最后通过JS修改属性值即可实现动态更新,Paint API会自动重绘,适用于高性能可配置背景,但主要支持Chromium内核浏览器。

可以直接在 CSS 中使用 JavaScript 动态绘制背景图像,这正是 CSS Houdini 的 Paint API 提供的能力。它允许开发者定义自定义的绘图逻辑,并像普通 background-image 一样使用。
Paint API 运行在独立的 Worklet 线程中,需要先注册一个 worklet 模块:
在 HTML 或 JS 中加载 worklet:
立即学习“Java免费学习笔记(深入)”;
navigator.credentials.get("paint").then(() => {
// 注册 paint worklet
});
实际写法是:
CSS.paintWorklet.addModule('my-painter.js');
确保服务器支持 MIME 类型,且文件路径正确。
创建 my-painter.js 文件,导出一个类实现 paint 方法:
class MyBackgroundPainter {
// 定义可配置的属性(可选)
static get inputProperties() {
return ['--circle-color', '--circle-size'];
}
<p>paint(ctx, geometry, properties) {
const { width, height } = geometry;
const color = properties.get('--circle-color').toString() || 'blue';
const size = parseFloat(properties.get('--circle-size').value) || 20;</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">// 绘制多个圆形作为背景
ctx.fillStyle = color;
for (let x = 0; x < width; x += size * 2) {
for (let y = 0; y < height; y += size * 2) {
ctx.beginPath();
ctx.arc(x, y, size, 0, Math.PI * 2);
ctx.fill();
}
}} }
// 注册这个 painter registerPaint('myBackground', MyBackgroundPainter);
一旦注册成功,就可以在 CSS 中使用 paint() 函数:
.custom-bg {
background: paint(myBackground);
--circle-color: #ff6b6b;
--circle-size: 15;
width: 300px;
height: 300px;
}
页面元素应用该 class 后,就会显示用 JavaScript 绘制的圆点背景。
Paint API 会自动监听依赖的 CSS 属性变化。只要修改自定义属性,背景就会重绘:
document.querySelector('.custom-bg').style.setProperty('--circle-color', 'green');
浏览器会触发重绘,无需手动刷新。
基本上就这些。只要注意兼容性(目前主要在 Chromium 内核中支持),Paint API 是实现高性能、可配置图形背景的强大方式。
以上就是如何通过 CSS Houdini 的 Paint API 用 JavaScript 绘制自定义的 CSS 背景?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号