js爱心怎么实现
实现爱心效果的方法
使用JavaScript和HTML5的Canvas可以创建一个动态的爱心效果。以下是一个简单的实现方法:
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
function drawHeart(x, y, size, color) {
ctx.save();
ctx.beginPath();
ctx.moveTo(x, y);
ctx.bezierCurveTo(
x, y - size / 2,
x - size, y - size / 2,
x - size, y
);
ctx.bezierCurveTo(
x - size, y + size / 3,
x, y + size,
x, y + size
);
ctx.bezierCurveTo(
x, y + size,
x + size, y + size / 3,
x + size, y
);
ctx.bezierCurveTo(
x + size, y - size / 2,
x, y - size / 2,
x, y
);
ctx.fillStyle = color;
ctx.fill();
ctx.restore();
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
const time = Date.now() * 0.001;
const x = canvas.width / 2 + Math.cos(time) * 50;
const y = canvas.height / 2 + Math.sin(time * 2) * 30;
drawHeart(x, y, 50, 'red');
requestAnimationFrame(animate);
}
animate();
使用CSS实现爱心效果
纯CSS也可以创建爱心形状,虽然不如JavaScript动态:

<div class="heart"></div>
<style>
.heart {
position: relative;
width: 100px;
height: 90px;
}
.heart:before, .heart:after {
content: "";
position: absolute;
top: 0;
width: 50px;
height: 80px;
background: red;
border-radius: 50px 50px 0 0;
}
.heart:before {
left: 50px;
transform: rotate(-45deg);
transform-origin: 0 100%;
}
.heart:after {
left: 0;
transform: rotate(45deg);
transform-origin: 100% 100%;
}
</style>
使用SVG创建爱心
SVG是创建矢量图形的另一种选择:
<svg width="100" height="100" viewBox="0 0 100 100">
<path d="M50,30
A20,20,0,1,1,50,70
A20,20,0,1,1,50,30
L50,85
Z" fill="red"/>
</svg>
数学公式绘制爱心
爱心可以用数学公式表示,以下是参数方程:

$x = 16\sin^3(t)$ $y = 13\cos(t) - 5\cos(2t) - 2\cos(3t) - \cos(4t)$
在JavaScript中实现:
function drawMathHeart() {
ctx.beginPath();
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);
ctx.lineTo(canvas.width/2 + x * 10, canvas.height/2 - y * 10);
}
ctx.fillStyle = 'pink';
ctx.fill();
}
这些方法可以根据需要选择使用,Canvas适合动态效果,CSS适合简单静态展示,SVG适合矢量图形,数学公式适合精确控制形状。






