CSS变量外加Paint API绘制透明格子实例页面
回到相关文章 »效果:
调整尺寸:
代码:
CSS代码:
.box {
width: 180px; height: 180px;
--color1: #fff;
--color2: #eee;
--units: 8;
background: paint(custom-grid);
}
HTML代码:
<div id="box" class="box">
<p>调整尺寸:<input type="range" id="range" min="6" value="8" max="20"></p>
</div>
JS代码:
if (window.CSS) {
CSS.paintWorklet.addModule('paint-grid.js');
}
// 改变尺寸变量
range.addEventListener('input', function () {
box.style.setProperty('--units', this.value);
});
paint-grid.js代码:
registerPaint('custom-grid', class {
// 获取3个变量
static get inputProperties() {
return [
'--color1',
'--color2',
'--units'
]
}
paint(context, size, properties) {
// 两个格子颜色
var color1 = properties.get('--color1').toString();
var color2 = properties.get('--color2').toString();
// 格子尺寸
var units = Number(properties.get('--units'));
// 横轴数轴循环遍历下
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);
}
}
}
});