const linearGradient = ctx.createLinearGradient(0, -100, 10, 100);
linearGradient.addColorStop(0, randomColor());
linearGradient.addColorStop(1, randomColor());
ctx.fillStyle = linearGradient;
function randomColor() {
// .padEnd(8, "9") 有时候会出现不满8位的十六进制颜色canvas会报错,使用padEnd填充满8位
return "#" + Math.round(Math.random() * 0xffffffff).toString(16).padEnd(8, "9");
}
const accuracy = 100; //渲染精度
function Heart(x, y, r) {
this.r = r;
this.x = x;
this.y = y;
const linearGradient = ctx.createLinearGradient(0, -100, 10, 100);
linearGradient.addColorStop(0, randomRGBA());
linearGradient.addColorStop(1, randomRGBA());
this.fillStyle = linearGradient;
const point = [];
for (let i = 0; i < accuracy; i++) {
const step = (i / accuracy) * (PI * 2);
const xx = r * (16 * pow(sin(step), 3));
const yy = r * (13 * cos(step) - 5 * cos(2 * step) - 2 * cos(3 * step) - cos(4 * step));
point.push(xx, yy);
};
this.point = point;
}
Heart.prototype.draw = function () {
ctx.save(); //保存 rotate translate 状态
ctx.beginPath();
ctx.translate(this.x, this.y);
ctx.rotate(PI);
const point = this.point;
for (let i = 0; i < point.length; i += 2) {
ctx.lineTo(point[i], point[i + 1]);
}
ctx.fillStyle = this.fillStyle;
ctx.fill();
ctx.closePath();
ctx.restore(); // 释放状态
}
new Heart(100, 200, 6).draw();
new Heart(200, 300, 7).draw();
new Heart(300, 300, 3).draw();
new Heart(600, 200, 8).draw();
new Heart(200, 500, 4).draw();