概述 Paint Worklet 允许以小型绘制程序扩展 CSS,使用 `CSS.paint()` 在样式中调用。适用于背景图样、装饰与轻量可视组件。需注意绘制频率与输入属性管理,以避免性能问题。 示例 ```js // main.js CSS.paintWorklet.addModule('/worklet.js') ``` ```js // worklet.js registerPaint('checkerboard', class { static get inputProperties() { return ['--size', 'background-color'] } paint(ctx, geom, props) { const size = parseInt(props.get('--size').toString() || '16', 10) for (let y = 0; y < geom.height; y += size) { for (let x = 0; x < geom.width; x += size) { ctx.fillStyle = ((x / size + y / size) % 2) ? '#eee' : '#ccc' ctx.fillRect(x, y, size, size) } } } }) ``` ```css .box { --size: 16; background: paint(checkerboard) } ``` 工程建议 - 输入与缓存:通过自定义属性减少重绘;避免在高频变化场景使用复杂绘制。 - 性能:控制区域尺寸与复杂度;结合 DevTools 性能面板分析重绘开销。 - 兼容:不支持环境回退到静态背景或图像;特性检测后启用。 参考与验证 - MDN CSS Painting API:https://developer.mozilla.org/docs/Web/API/CSS_Painting_API - web.dev Houdini 指南:https://web.dev/articles/houdini - Chrome 平台文档:https://developer.chrome.com/docs/web-platform/css-paint-api/

发表评论 取消回复