js实现心形线
实现心形线的 JavaScript 方法
心形线(Cardioid)是一种极坐标方程曲线,可以通过以下数学公式描述:
- 极坐标方程:$r = a(1 + \cos\theta)$
- 参数方程:
$x = a(2\cos t - \cos 2t)$
$y = a(2\sin t - \sin 2t)$
使用 Canvas 绘制心形线
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 400;
// 心形线参数方程
function cardioid(t, scale) {
return {
x: scale * (16 * Math.pow(Math.sin(t), 3)),
y: scale * (13 * Math.cos(t) - 5 * Math.cos(2*t) - 2 * Math.cos(3*t) - Math.cos(4*t))
};
}
// 绘制心形
ctx.beginPath();
ctx.strokeStyle = 'red';
ctx.fillStyle = 'pink';
for (let t = 0; t < 2 * Math.PI; t += 0.01) {
const point = cardioid(t, 10);
const x = point.x + canvas.width / 2;
const y = -point.y + canvas.height / 2; // 反转Y轴
if (t === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
}
ctx.closePath();
ctx.fill();
ctx.stroke();
使用 SVG 绘制心形线
const svgNS = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(svgNS, "svg");
svg.setAttribute("width", "400");
svg.setAttribute("height", "400");
document.body.appendChild(svg);
let pathData = "";
for (let t = 0; t <= 2 * Math.PI; t += 0.01) {
const x = 200 + 16 * Math.pow(Math.sin(t), 3) * 10;
const y = 200 - (13 * Math.cos(t) - 5 * Math.cos(2*t) - 2 * Math.cos(3*t) - Math.cos(4*t)) * 10;
if (t === 0) {
pathData += `M ${x} ${y}`;
} else {
pathData += ` L ${x} ${y}`;
}
}
const path = document.createElementNS(svgNS, "path");
path.setAttribute("d", pathData);
path.setAttribute("fill", "pink");
path.setAttribute("stroke", "red");
svg.appendChild(path);
使用 Three.js 绘制 3D 心形
import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 创建心形几何体
const heartShape = new THREE.Shape();
heartShape.moveTo(0, 0);
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);
heartShape.lineTo(x, y);
}
const geometry = new THREE.ExtrudeGeometry(heartShape, {
depth: 1,
bevelEnabled: true,
bevelSize: 0.5
});
const material = new THREE.MeshPhongMaterial({ color: 0xff69b4 });
const heart = new THREE.Mesh(geometry, material);
scene.add(heart);
camera.position.z = 30;
function animate() {
requestAnimationFrame(animate);
heart.rotation.x += 0.01;
heart.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
数学公式变体
经典心形线公式:
$r = 1 - \cos\theta$
或参数方程:
$x = \cos t \cdot (1 + \cos t)$
$y = \sin t \cdot (1 + \cos t)$
更复杂的心形公式(如上文代码所用):
$x = 16\sin^3 t$
$y = 13\cos t - 5\cos 2t - 2\cos 3t - \cos 4t$







