我想在 html 5 canvas 中绘制心形。我知道一个可以生成心形坐标的数学方程式。我已经在 javascript 函数中实现了这些方程式,并且该函数正在返回坐标。一切正常,心脏在 Canvas 上绘制。但心形大小是固定的。我尝试了很多方法来增加它的大小,但都没有用。你能帮我改变方程式以获得所需的尺寸吗?
这是方程式:-
x = 16 sin(t) * sin(t) * sin(t)
y = 13 余弦(t)- 5 余弦(2t)- 2 余弦(3t)- 余弦(4t)
我不知道如何在这个编辑器中显示力量,所以我将 sin(t) 乘以三倍。
这是 javascript 函数:-
function getCordinatesOnHeartShape(x, y) {
var cordinates = [];
var pi = Math.PI;
for(var t = 0; t <= 360; t++) {
var tr = (t * pi)/180;
cordinates[t] = {
x : (x - (16 * Math.sin(tr) * Math.sin(tr) * Math.sin(tr))),
y : (y -((13 * Math.cos(tr)) - (5 * Math.cos(2 * tr)) - (2 * Math.cos(3 * tr)) - Math.cos(4 * tr)))
};
}
return cordinates;
}
这是我在 Canvas 上的位置 (200, 200) 上绘制心形的方法:-
ctx.beginPath();
var hc = getCordinatesOnHeartShape(200, 200);
for(var i = 0; i < hc.length; i++) {
ctx.lineTo(hc[i].x, hc[i].y);
}
ctx.fill();
这会在位置 (200, 200) 上绘制一个固定大小的心,我想更改它的大小。谢谢。
最佳答案
您可以使用 Canvas ctx.save()
、ctx.restore()
和 ctx.translate()
函数来完成。
这是完整的代码。
希望对你有帮助。
let canvas = document.getElementById('c');
let canvasWidth = canvas.width;
let canvasHeight = canvas.height;
let ctx = canvas.getContext('2d');
function getCordinatesOnHeartShape(x, y) {
var cordinates = [];
var pi = Math.PI;
for (var t = 0; t <= 360; t++) {
var tr = (t * pi) / 180;
cordinates[t] = {
x: (x - (16 * Math.sin(tr) * Math.sin(tr) * Math.sin(tr))),
y: (y - ((13 * Math.cos(tr)) - (5 * Math.cos(2 * tr)) - (2 * Math.cos(3 * tr)) - Math.cos(4 * tr)))
};
}
return cordinates;
}
let size = 1;
let a = 0;
let x = 100;
let y = 100;
function animate() {
a += 0.05;
ctx.fillStyle = 'black';
ctx.fillRect(-canvasWidth / 2, -canvasHeight / 2, canvasWidth, canvasHeight);
size = 2 - Math.cos(a);
ctx.resetTransform();
ctx.translate(x, y);
ctx.save();
ctx.beginPath();
ctx.fillStyle = 'red';
var hc = getCordinatesOnHeartShape(x, y);
ctx.translate(-size * x, -size * y);
ctx.scale(size, size);
for (var i = 0; i < hc.length; i++) {
ctx.lineTo(hc[i].x, hc[i].y);
}
ctx.fill();
ctx.restore();
requestAnimationFrame(animate);
}
animate();
<!DOCTYPE html>
<html lang="en">
<head>
<title>Heart</title>
</head>
<body>
<canvas id="c" width="200" height="200"></canvas>
</body>
</html>
关于javascript - 如何在 Canvas 上增加/减少这个心形的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54198165/