CSS对象
CSS.paintWorklet.addModule 是一个新方法,具体参见 https://developer.mozilla.org/en-US/docs/Web/API/Worklet/addModule
index.html
1<!DOCTYPE html>2<html lang="en">34<head>5 <meta charset="UTF-8">6 <meta http-equiv="X-UA-Compatible" content="IE=edge">7 <meta name="viewport" content="width=device-width, initial-scale=1.0">8 <title>Document</title>9 <style>10 .radius {11 width: 200px;12 height: 200px;13 background: paint(transparent-grid)14 }15 </style>16 <script>17 CSS.paintWorklet.addModule('jsbackground.js');18 </script>19</head>2021<body>22 <div class="radius"></div>23</body>2425</html>
jsbackground.js
1// transparent-grid命名和CSS中的对应2registerPaint(3 "smooth-corners",4 class {5 paint(ctx, size) {6 ctx.strokeStyle = "black";7 ctx.lineWidth = 4;8 ctx.beginPath();9 ctx.arc(200, 200, 50, 0, 2 * Math.PI);10 ctx.stroke();11 ctx.closePath();12 }13 }14);1516registerPaint(17 "transparent-grid",18 class {19 paint(context, size) {20 // 两个格子颜色21 var color1 = "#fff",22 color2 = "#eee";23 // 格子尺寸24 var units = 8;25 // 横轴数轴循环遍历下26 for (var x = 0; x < size.width; x += units) {27 for (var y = 0; y < size.height; y += units) {28 context.fillStyle = (x + y) % (units * 2) === 0 ? color1 : color2;29 context.fillRect(x, y, units, units);30 }31 }32 }33 }34);
效果
svg矢量图,可以用来做图片编辑时的背景