使用 CSS Paint API 的惯用方法似乎是:
- Create a
xyz.js
file
- 填充一个包含以下内容的类
paint(ctx, geom, properties)
功能
- Call
registerPaint
,将类作为参数传递
- Call
CSS.paintWorklet.addModule('xyz.js')
从你的index.html
- 在 CSS 中应用绘制工作集,例如
background-image: paint(myPaintWorklet);
更多详细信息请参见此处:https://developers.google.com/web/updates/2018/01/paintapi https://developers.google.com/web/updates/2018/01/paintapi
但必须加载单独的 .js 文件会影响性能。
有没有办法内联 PaintWorklet 以便不需要单独的 .js 文件?
一种方法是使用数据 URL https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs。演示:(至少在 chrome 73 上适用于我)。示例取自here https://developers.google.com/web/updates/2018/01/paintapi
<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 https://developer.mozilla.org/en-US/docs/Web/API/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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)