PaintWorkletGlobalScope: registerPaint() 方法

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

實驗性: 這是一項實驗性技術
在生產中使用此技術之前,請仔細檢查瀏覽器相容性表格

PaintWorkletGlobalScope 介面的 registerPaint() 方法用於註冊一個類,該類可以以程式設計方式生成 CSS 屬性期望的檔案影像。

語法

js
registerPaint(name, classRef)

引數

name

要註冊的工作let類的名稱。

classRef

對實現該工作let的類的引用。

返回值

無(undefined)。

異常

TypeError

當引數之一無效或缺失時丟擲。

InvalidModificationError DOMException

當具有指定名稱的工作let已存在時丟擲。

示例

以下展示瞭如何註冊一個示例工作let模組。這應該放在一個單獨的 JS 檔案中。請注意,registerPaint() 是在沒有 PaintWorkletGlobalScope 引用的情況下呼叫的。該檔案本身是透過 CSS.paintWorklet.addModule() 載入的(在此處記錄在 PaintWorklet 的父類 Worklet.addModule() 中)。

js
/* checkboardWorklet.js */

class CheckerboardPainter {
  paint(ctx, geom, properties) {
    // 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);

使用 paintworklet 的第一步是使用 registerPaint() 函式定義 paint worklet,如上所示。要使用它,你需要使用 CSS.paintWorklet.addModule() 方法進行註冊。

js
CSS.paintWorklet.addModule("checkboardWorklet.js");

然後,你可以在 CSS 中任何接受 <image> 值的地方使用 paint() CSS 函式。

css
li {
  background-image: paint(checkerboard);
}

規範

規範
CSS Painting API Level 1
# dom-paintworkletglobalscope-registerpaint

瀏覽器相容性

另見