一种方法是使用Data URLs。演示:(至少在 chrome 73 上为我工作)。取自此处的示例
<style>
textarea {
background-image: paint(checkerboard);
}
</style>
<textarea></textarea>
<script>
CSS.paintWorklet.addModule(`data:application/javascript;charset=utf8,${encodeURIComponent(`
// checkerboard.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);
`)}`)
</script>
另一种方法是创建一个Blob
并将 blob URL 传递给addModule
函数。这看起来不那么骇人听闻。演示:
<style>
textarea {
background-image: paint(checkerboard);
}
</style>
<textarea></textarea>
<script>
CSS.paintWorklet.addModule(URL.createObjectURL(new Blob([`
// checkerboard.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);
`], {type: "application/javascript"})))
</script>