可编程的css背景属性CSS Paint API
CSS Paint API只是一W3C规范的一部分,它特别允许您调用paint()函数,无论您通常在需要图像的地方编写一个值。一个常见的例子是background image属性,您可以在其中使用url()函数链接到图像文件,如下所示:
area { background-image: url('assets/myimage.jpg'); }css paint api允许您调用paint()函数,并传递通过javascript定义的paint工作集。把它想象成一段代码,它允许你以编程方式画出你喜欢的任何东西。因为它是Javascript,所以你也可以使它成为动态的。API本身非常类似于HTML5<canvas>API。
area { background-image: paint(awesomePattern); };
无论如何,让我们来看一下如何创建代码来使用它。
第一步,编写css
section { background-image: url('fallback.png'); background-image: paint(awesomePattern); };第二步,在主js中加载负责绘画的js
CSS.paintWorklet.addModule('patternWorklet.js');第三步,编写patternWorklet.js
registerPaint('awesomePattern', Shape); class Shape { paint(ctx, geom, properties) { ctx.strokeStyle = 'white'; ctx.lineWidth = 4; ctx.beginPath(); ctx.arc( 200, 200, 50, 0, 2*Math.PI); ctx.stroke(); ctx.closePath(); } }完整的示例如下,可在线运行和编辑
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Simple Circle: CSS Paint API Example</title> <style> body { margin: 0px; padding: 0px; } #screen { box-sizing: border-box; margin: 10px; padding: 0px; width: calc(100vw - 20px); height: calc(100vh - 20px); background-image: paint(testshape); } </style> </head> <body translate="no"> <section id="screen"> </section> <script> CSS.paintWorklet.addModule('/bfwrepo/js/TestShape.js'); </script> </body> </html>
网友评论0