PaintWorklet - Web APIs 编辑

Experimental

This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The PaintWorklet interface of the CSS Painting API programmatically generates an image where a CSS property expects a file. Access this interface through CSS.paintWorklet.

Properties

PaintWorklet.devicePixelRatio
Returns the current device's ratio of physical pixels to logical pixels.

Event handlers

None.

Methods

This interface inherits methods from Worklet.

PaintWorklet.registerPaint()
Registers a class programmatically generate an image where a CSS property expects a file.
CSS.PaintWorklet.addModule()
The addModule() method, inhertied from the Worklet interface loads the module in the given JavaScript file and adds it to the current PaintWorklet.

Examples

The following three examples go together to show creating, loading, and using a PaintWorklet.

Create a PaintWorklet

The following shows an example worklet module. This should be in a separate js file. Note that registerPaint() is called without a reference to PaintWorklet.

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);

Load a PaintWorklet

The following example demonstrates loading the above worklet from its js file and does so by feature detection.

<script>
  if ('paintWorklet' in CSS) {
    CSS.paintWorklet.addModule('checkerboard.js');
  }
</script>

Use a PaintWorklet

This example shows how to use a PaintWorklet in a stylesheet, including the simplest way to provide a fallback if PaintWorklet isn't supported. 

<style>
  textarea {
    background-image: url(checkerboard);
    background-image: paint(checkerboard);
  }
</style>
<textarea></textarea>

You can also use the @supports at-rule.

@supports (background: paint(id)) {
  background-image: paint(checkerboard);
}

Specifications

SpecificationStatusComment
CSS Painting API Level 1
The definition of 'PaintWorkletGlobalScope' in that specification.
Working DraftInitial definition.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:143 次

字数:5441

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文