CSS 中的 paint() 函数用于定义使用 PaintWorklet 生成的 <image> 值。PaintWorklet 帮助开发者定义一些自定义绘画函数,这些函数可以直接在 CSS 中用于各种属性,如背景、边框等。
语法
paint(workletName, ...parameters)
在上面的语法中,函数 paint() 包含以下参数:
- workletName:指定已注册的工作单元的名称。
- parameters:指定要传递给 PaintWorklet 的其他参数。它是可选的。
CSS paint() - 创建 Paint Worklet
以下示例演示了 paint() 函数的用法。
您需要创建一个绘制工作集。要定义 paint worklet,您需要使用 CSS.paintWorklet.addModule('board.js') 加载 CSS Paint Worklet。要注册 Paint Worklet 类,您需要使用 registerPaint 函数。
在以下示例中,将创建一个绘图工作卷,并将其用作 <textarea> 的背景图像。使用 <textarea>因为它是可调整大小的。
注意:与几乎所有新 API 一样,CSS Paint API 只能通过 HTTPS(或 localhost)使用。
<html>
<head>
<script>
if ("paintWorklet" in CSS) {
CSS.paintWorklet.addModule("board.js");
}
</script>
<style>
textarea {
background-image: url(board);
background-image: paint(board);
}
</style>
</head>
<body>
<h2>CSS Function paont()</h2>
<textarea></textarea>
</body>
</html>
Javascript board.js如下:
class TestPainter {
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;
// const dpr = window.devicePixelRatio;
// const dpr = Window.devicePixelRatio;
// Use `ctx` as if it was a normal canvas
const colors = ["yellow", "black", "white"];
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 the class under a particular name
registerPaint("board", TestPainter);