js实现剪纸
使用Canvas实现剪纸效果
在JavaScript中实现剪纸效果可以通过Canvas API完成。以下是核心实现方法:
创建Canvas元素并获取上下文
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 600;
document.body.appendChild(canvas);
绘制剪纸基础形状
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(400, 300, 200, 0, Math.PI * 2);
ctx.fill();
添加剪纸镂空效果
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath();
ctx.moveTo(400, 100);
ctx.lineTo(500, 500);
ctx.lineTo(300, 500);
ctx.closePath();
ctx.fill();
使用SVG实现剪纸效果
SVG更适合创建矢量剪纸图案:
创建SVG元素
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('width', '800');
svg.setAttribute('height', '600');
document.body.appendChild(svg);
添加剪纸路径

const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute('d', 'M400,300 a200,200 0 1,0 0.1,0 z');
path.setAttribute('fill', 'red');
svg.appendChild(path);
添加镂空效果
const hole = document.createElementNS("http://www.w3.org/2000/svg", "path");
hole.setAttribute('d', 'M400,100 L500,500 L300,500 Z');
hole.setAttribute('fill', 'white');
svg.appendChild(hole);
使用CSS Clip-path实现简单剪纸
对于简单的剪纸效果,CSS也能实现:
HTML结构
<div class="paper-cut"></div>
CSS样式

.paper-cut {
width: 400px;
height: 400px;
background-color: red;
clip-path: polygon(
50% 0%,
80% 100%,
20% 100%
);
}
复杂剪纸图案生成算法
对于需要程序化生成的复杂剪纸图案:
生成随机剪纸图案
function generateRandomPaperCut(ctx) {
const centerX = 400;
const centerY = 300;
const radius = 200;
const points = 12;
ctx.beginPath();
for(let i = 0; i < points; i++) {
const angle = (i / points) * Math.PI * 2;
const randomRadius = radius * (0.7 + Math.random() * 0.3);
const x = centerX + Math.cos(angle) * randomRadius;
const y = centerY + Math.sin(angle) * randomRadius;
if(i === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
}
ctx.closePath();
ctx.fill();
}
动画剪纸效果
为剪纸添加动画效果:
旋转剪纸动画
let angle = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(400, 300);
ctx.rotate(angle);
ctx.translate(-400, -300);
// 绘制剪纸
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(400, 300, 200, 0, Math.PI * 2);
ctx.fill();
ctx.globalCompositeOperation = 'destination-out';
// 添加镂空图案
ctx.restore();
angle += 0.01;
requestAnimationFrame(animate);
}
animate();






