js实现心形线
使用 Canvas 绘制心形线
通过 HTML5 Canvas 和 JavaScript 可以绘制心形线。以下是基于极坐标方程的实现代码:
const canvas = document.getElementById('heartCanvas');
const ctx = canvas.getContext('2d');
function drawHeart() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
// 心形线参数方程 (极坐标)
for (let theta = 0; theta < 2 * Math.PI; theta += 0.01) {
const r = 16 * Math.pow(Math.sin(theta), 3); // 心形线方程
const x = canvas.width/2 + r * Math.cos(theta) * 10;
const y = canvas.height/2 - r * Math.sin(theta) * 10;
if (theta === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
}
ctx.fillStyle = 'red';
ctx.fill();
}
drawHeart();
使用 SVG 绘制心形线
通过 SVG 路径命令可以创建更精确的心形图形:
const svg = document.getElementById('heartSvg');
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
// 贝塞尔曲线绘制心形
path.setAttribute('d', `
M 100,100
C 100,50 25,25 100,150
C 175,25 100,50 100,100
Z
`);
path.setAttribute('fill', 'red');
svg.appendChild(path);
使用 CSS 绘制心形
纯 CSS 实现的心形效果(非数学精确曲线):
.heart {
width: 100px;
height: 100px;
background-color: red;
transform: rotate(45deg);
position: relative;
}
.heart:before, .heart:after {
content: '';
width: 100px;
height: 100px;
background-color: red;
border-radius: 50%;
position: absolute;
}
.heart:before {
top: -50px;
left: 0;
}
.heart:after {
top: 0;
left: -50px;
}
参数方程说明
心形线的数学表达式(极坐标): $$ r = a(1 - \sin\theta) $$
笛卡尔坐标系下的参数方程: $$ x = a(2\cos t - \cos 2t) $$ $$ y = a(2\sin t - \sin 2t) $$
其中参数 $a$ 控制心形大小,$t$ 是角度参数(通常 $0 \leq t \leq 2\pi$)。
动画效果实现
为心形线添加跳动动画:

let scale = 1;
let growing = true;
function animateHeart() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(canvas.width/2, canvas.height/2);
// 缩放动画
scale = growing ? scale + 0.01 : scale - 0.01;
if (scale > 1.2) growing = false;
if (scale < 0.8) growing = true;
ctx.scale(scale, scale);
// 绘制心形
ctx.beginPath();
for (let theta = 0; theta < 2 * Math.PI; theta += 0.01) {
const r = 16 * Math.pow(Math.sin(theta), 3);
const x = r * Math.cos(theta) * 5;
const y = -r * Math.sin(theta) * 5;
ctx.lineTo(x, y);
}
ctx.fillStyle = 'red';
ctx.fill();
ctx.restore();
requestAnimationFrame(animateHeart);
}
animateHeart();






