CSS 函式 - paint()



CSS 中的 paint() 函式用於定義由 PaintWorklet 生成的 <image> 值。PaintWorklet 幫助開發人員定義一些自定義繪畫函式,這些函式可以直接在 CSS 中用於各種屬性,例如背景、邊框等。

語法

paint(workletName, ...parameters)

在以上語法中,函式 paint() 包含以下引數

  • workletName:指定已註冊的工作執行緒的名稱。

  • parameters:指定傳遞給 PaintWorklet 的其他引數。它是可選的。

CSS paint() - 建立 Paint Worklet

以下示例演示了 paint() 函式的使用。

您需要建立一個繪畫工作執行緒。要定義一個繪畫工作執行緒,您需要使用 CSS.paintWorklet.addModule('board.js') 載入一個 CSS 繪畫工作執行緒。要註冊一個繪畫工作執行緒類,您需要使用 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);
廣告

© . All rights reserved.