CSS Paint API デモ
Houdini Paint APIを使用してCanvasベースのカスタムCSS背景を作成
生成コード
<!DOCTYPE html>
<html>
<head>
<style>
.paint-demo {
width: 400px;
height: 300px;
background: paint(grid-pattern);
--grid-size: 20;
--grid-color: rgba(0,0,0,0.1);
}
</style>
</head>
<body>
<div class="paint-demo"></div>
<script>
// Workletファイルを別途作成して読み込む
CSS.paintWorklet.addModule('paint-worklet.js');
</script>
</body>
</html>
<!-- paint-worklet.js の内容 -->
<!--
// Paint Workletコード例
class GridPattern {
static get inputProperties() {
return ['--grid-size', '--grid-color'];
}
paint(ctx, size, properties) {
const gridSize = parseInt(properties.get('--grid-size')) || 20;
const color = properties.get('--grid-color').toString() || 'rgba(0,0,0,0.1)';
ctx.strokeStyle = color;
ctx.lineWidth = 1;
// 縦線
for (let x = 0; x < size.width; x += gridSize) {
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, size.height);
ctx.stroke();
}
// 横線
for (let y = 0; y < size.height; y += gridSize) {
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(size.width, y);
ctx.stroke();
}
}
}
registerPaint('grid-pattern', GridPattern);
-->使い方:
- Paint Workletコードを編集
- ペイント名を設定(registerPaintの第一引数と一致させる)
- 必要なCSS変数を追加・編集
- 「プレビューに適用」をクリック
- 生成コードをコピーしてHTMLファイルに使用
※ CSS Paint APIはChrome/Edgeでのみ動作します