js实现剪纸
使用Canvas实现剪纸效果
在JavaScript中实现剪纸效果可以通过HTML5的Canvas API来完成。以下是一个基本的实现方法:
const canvas = document.getElementById('paperCutCanvas');
const ctx = canvas.getContext('2d');
// 设置画布背景色
ctx.fillStyle = '#f5f5f5';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 创建剪纸图案
ctx.fillStyle = '#e74c3c';
ctx.beginPath();
ctx.arc(150, 150, 100, 0, Math.PI * 2);
ctx.fill();
// 添加剪纸细节
ctx.fillStyle = '#f5f5f5';
ctx.beginPath();
ctx.arc(150, 150, 80, 0, Math.PI * 2);
ctx.fill();
使用SVG实现剪纸效果
SVG也是实现剪纸效果的理想选择,因为它支持矢量图形和分层:
<svg width="300" height="300">
<!-- 背景 -->
<rect width="100%" height="100%" fill="#f5f5f5"/>
<!-- 剪纸图案 -->
<circle cx="150" cy="150" r="100" fill="#e74c3c"/>
<circle cx="150" cy="150" r="80" fill="#f5f5f5"/>
<!-- 细节装饰 -->
<path d="M150,50 Q200,100 150,150 Q100,100 150,50"
fill="none" stroke="#c0392b" stroke-width="2"/>
</svg>
使用CSS和HTML元素
对于简单的剪纸效果,可以结合CSS和HTML元素:
<div class="paper-cut">
<div class="outer-circle"></div>
<div class="inner-circle"></div>
<div class="decoration"></div>
</div>
<style>
.paper-cut {
position: relative;
width: 300px;
height: 300px;
background-color: #f5f5f5;
}
.outer-circle {
position: absolute;
width: 200px;
height: 200px;
border-radius: 50%;
background-color: #e74c3c;
top: 50px;
left: 50px;
}
.inner-circle {
position: absolute;
width: 160px;
height: 160px;
border-radius: 50%;
background-color: #f5f5f5;
top: 70px;
left: 70px;
}
</style>
添加动画效果
为剪纸效果添加简单的动画:
// 使用GSAP库实现动画
gsap.to(".outer-circle", {
rotation: 360,
duration: 5,
repeat: -1,
ease: "none"
});
// 或者使用纯CSS动画
@keyframes rotate {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.outer-circle {
animation: rotate 5s linear infinite;
}
复杂剪纸图案生成
对于更复杂的剪纸图案,可以使用算法生成:
function generatePaperCutPattern(ctx, complexity = 5) {
ctx.beginPath();
for(let i = 0; i < complexity; i++) {
const angle = (i / complexity) * Math.PI * 2;
const radius = 50 + Math.random() * 50;
const x = 150 + Math.cos(angle) * radius;
const y = 150 + Math.sin(angle) * radius;
if(i === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
}
ctx.closePath();
ctx.fill();
}
// 使用
ctx.fillStyle = '#3498db';
generatePaperCutPattern(ctx, 8);
响应式剪纸设计
确保剪纸效果在不同设备上都能正常显示:

function resizeCanvas() {
const container = document.getElementById('canvasContainer');
canvas.width = container.clientWidth;
canvas.height = container.clientHeight;
// 重新绘制剪纸
drawPaperCut();
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();






