CSS Paint API绘制透明格子背景实例页面
展示
代码
-
HTML:
<div class="box"></div>
CSS:
.box { width: 180px; height: 180px; background: paint(transparent-grid); }
-
页面内JS:
if (window.CSS) { CSS.paintWorklet.addModule('paint-grid.js'); }
paint-grid.js代码:
registerPaint('transparent-grid', class { paint(context, size) { // 两个格子颜色 var color1 = '#fff'; var color2 = '#eee'; // 格子尺寸 var units = 8; // 横轴数轴循环遍历下 for (var x = 0; x < size.width; x += units) { for (var y = 0; y < size.height; y += units) { context.fillStyle = (x + y) % (units * 2) === 0 ? color1 : color2; context.fillRect(x, y, units, units); } } } });