js实现爱心
使用Canvas绘制爱心
通过HTML5的Canvas API可以绘制一个动态或静态的爱心形状。以下是基础实现代码:
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
canvas.width = 200;
canvas.height = 200;
ctx.beginPath();
ctx.moveTo(100, 100);
ctx.bezierCurveTo(100, 30, 30, 30, 30, 100);
ctx.bezierCurveTo(30, 170, 100, 170, 100, 200);
ctx.bezierCurveTo(100, 170, 170, 170, 170, 100);
ctx.bezierCurveTo(170, 30, 100, 30, 100, 100);
ctx.fillStyle = 'red';
ctx.fill();
使用CSS和HTML创建爱心
纯CSS实现方案,适合不需要交互的静态展示:

<div class="heart"></div>
<style>
.heart {
width: 100px;
height: 100px;
background: red;
transform: rotate(45deg);
position: relative;
}
.heart:before, .heart:after {
content: '';
width: 100px;
height: 100px;
background: red;
border-radius: 50%;
position: absolute;
}
.heart:before {
top: -50px;
left: 0;
}
.heart:after {
top: 0;
left: -50px;
}
</style>
动态跳动爱心动画
结合CSS动画实现跳动效果:

const style = document.createElement('style');
style.textContent = `
@keyframes heartbeat {
0% { transform: scale(1); }
25% { transform: scale(1.1); }
50% { transform: scale(1); }
75% { transform: scale(1.1); }
100% { transform: scale(1); }
}
.heartbeat {
animation: heartbeat 1s infinite;
}`;
document.head.appendChild(style);
// 添加到之前CSS爱心的示例中
document.querySelector('.heart').classList.add('heartbeat');
使用SVG绘制爱心
矢量图形方案,适合需要缩放的情况:
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', '200');
svg.setAttribute('height', '200');
document.body.appendChild(svg);
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute('d', 'M100 30 C50 0 0 50 50 100 S100 180 150 100 S250 0 100 30 Z');
path.setAttribute('fill', 'red');
svg.appendChild(path);
数学函数生成爱心曲线
基于心形曲线方程的生成方法:
function drawHeart() {
const points = [];
for (let t = 0; t < 2 * Math.PI; t += 0.01) {
const x = 16 * Math.pow(Math.sin(t), 3);
const y = 13 * Math.cos(t) - 5 * Math.cos(2*t) - 2 * Math.cos(3*t) - Math.cos(4*t);
points.push([x + 50, -y + 50]);
}
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 100;
canvas.height = 100;
ctx.beginPath();
points.forEach(([x, y], i) => {
i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
});
ctx.closePath();
ctx.fillStyle = 'red';
ctx.fill();
document.body.appendChild(canvas);
}
drawHeart();






