PaintWorkletGlobalScope

可用性有限

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

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

PaintWorkletGlobalScope 介面是 CSS 繪畫 API 的一部分,它代表了在繪畫 Worklet 內部可用的全域性物件。

隱私問題

為避免洩露訪問過的連結,該功能在基於 Chrome 的瀏覽器中目前被停用,不適用於帶有 href 屬性的 <a> 元素,也不適用於這些元素的子元素。詳情請參閱以下內容:

例項屬性

此介面繼承自 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

瀏覽器相容性

另見