首先找了一个心形线公式:
x=12*sin(t)-4*sin(3*t)
y=13*cos(t)-5*cos(2*t)-2*cos(3*t)-cos(4*t)
代码如下:
function heart() {
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
//设置初始弧度
let radian = 0;
//设置弧度增量,每次增加1°
let radian_add = Math.PI / 180;
//开始绘图
ctx.beginPath();
// 重新映射画布上的 (0,0) 位置
ctx.translate(250, 200);
// 设置绘制起点
ctx.moveTo(getX(radian), getY(radian));
// 弧度小于等于360°
while (radian <= Math.PI * 2) {
//每增加一次弧度,绘制一条线
radian += radian_add;
X = getX(radian);
Y = getY(radian);
ctx.lineTo(X, Y);
}
ctx.strokeStyle = "red";
ctx.stroke();
}
//获取心型线的X坐标,放大15倍
function getX(t) {
return 15 * (12 * Math.sin(t) - 4 * Math.sin(3 * t));
}
//获取心型线的Y坐标,放大15倍
function getY(t) {
return (
-15 *
(13 * Math.cos(t) -
5 * Math.cos(2 * t) -
2 * Math.cos(3 * t) -
Math.cos(4 * t))
);
}
实现效果如下,可在线查看效果
