js实现剪纸
JavaScript 实现剪纸效果
在网页中实现剪纸效果通常涉及Canvas绘图或CSS剪裁技术。以下是两种常见的方法:
使用Canvas绘制剪纸图案
通过Canvas的路径绘制和填充功能可以创建自定义剪纸图案:
const canvas = document.getElementById('paperCutCanvas');
const ctx = canvas.getContext('2d');
// 设置剪纸颜色
ctx.fillStyle = '#e74c3c';
// 绘制对称剪纸图案
ctx.beginPath();
ctx.moveTo(100, 50);
ctx.lineTo(150, 150);
ctx.lineTo(50, 150);
ctx.closePath();
ctx.fill();
// 添加镂空效果
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath();
ctx.arc(100, 100, 30, 0, Math.PI * 2);
ctx.fill();
关键点:
- 使用
globalCompositeOperation实现镂空效果 - 通过路径绘制定义剪纸形状
- 多层路径叠加可创建复杂图案
使用CSS clip-path实现
通过CSS的剪裁路径可以实现简单的剪纸效果:
.paper-cut {
width: 200px;
height: 200px;
background-color: #e74c3c;
clip-path: polygon(
50% 0%, 80% 20%,
100% 50%, 80% 80%,
50% 100%, 20% 80%,
0% 50%, 20% 20%
);
}
动态修改剪裁路径:
const element = document.querySelector('.paper-cut');
element.style.clipPath = 'polygon(30% 0%, 70% 0%, 100% 30%, 100% 70%, 70% 100%, 30% 100%, 0% 70%, 0% 30%)';
SVG结合方案
使用SVG作为剪裁源可实现更精细的控制:
<svg width="0" height="0">
<defs>
<clipPath id="paperCutPattern">
<path d="M10,10 L50,100 L100,10"/>
</clipPath>
</defs>
</svg>
<div style="width:200px; height:200px; background:red; clip-path: url(#paperCutPattern)"></div>
动画效果实现
为剪纸添加展开动画:
function animateCutPaper(element, duration) {
let progress = 0;
const timer = setInterval(() => {
progress += 1/duration;
const path = generatePath(progress); // 根据进度生成路径
element.style.clipPath = path;
if(progress >= 1) clearInterval(timer);
}, 16);
}
实现要点:
- 使用requestAnimationFrame优化性能
- 通过插值算法平滑过渡路径
- 可结合GSAP等动画库增强效果
以上方法可根据项目需求选择或组合使用,Canvas适合复杂动态图案,CSS方案更轻量,SVG则兼具精度和可缩放性。







