隐私问题
为避免泄露访问过的链接,该功能在基于 Chrome 的浏览器中目前被禁用,不适用于带有 href 属性的 <a> 元素,也不适用于这些元素的子元素。详情请参阅以下内容:
- CSS 绘画 API 的 隐私注意事项部分
- CSS 绘画 API 规范问题 “CSS Paint API 泄露浏览历史”
实例属性
此接口继承自 WorkletGlobalScope 的属性。
PaintWorkletGlobalScope.devicePixelRatio只读 实验性-
返回当前设备的物理像素与逻辑像素的比例。
实例方法
此接口继承自 WorkletGlobalScope 的方法。
PaintWorkletGlobalScope.registerPaint()实验性-
注册一个类,用于以编程方式生成 CSS 属性期望文件的图像。
示例
以下三个示例共同展示了如何创建、加载和使用绘画 Worklet。
创建绘画 worklet
以下示例展示了一个 worklet 模块。它应该放在一个单独的 JavaScript 文件中。请注意,registerPaint() 的调用不带对绘画 Worklet 的引用。
js
class CheckerboardPainter {
paint(ctx, geom, properties) {
// The global object here is a PaintWorkletGlobalScope
// Methods and properties can be accessed directly
// as global features or prefixed using self
const dpr = self.devicePixelRatio;
// Use `ctx` as if it was a normal canvas
const colors = ["red", "green", "blue"];
const size = 32;
for (let y = 0; y < geom.height / size; y++) {
for (let x = 0; x < geom.width / size; x++) {
const color = colors[(x + y) % colors.length];
ctx.beginPath();
ctx.fillStyle = color;
ctx.rect(x * size, y * size, size, size);
ctx.fill();
}
}
}
}
// Register our class under a specific name
registerPaint("checkerboard", CheckerboardPainter);
加载绘画 worklet
以下示例通过特性检测来演示如何从其 JavaScript 文件加载上述 worklet。
js
if ("paintWorklet" in CSS) {
CSS.paintWorklet.addModule("checkerboard.js");
}
使用绘画 worklet
此示例展示了如何在样式表中(包括最简单的提供回退的方式,以防 CSS.paintWorklet 不受支持)使用绘画 Worklet。
css
textarea {
background-image: url("checkerboard.png"); /* Fallback */
background-image: paint(checkerboard);
}
您也可以使用 @supports 规则。
css
@supports (background: paint(id)) {
textarea {
background-image: paint(checkerboard);
}
}
规范
| 规范 |
|---|
| CSS Painting API Level 1 # paintworkletglobalscope |
浏览器兼容性
加载中…