我正在尝试在 Canvas 上旋转 N 边多边形,但我遇到了坐标问题。这些形状似乎围绕其自身之外的原点旋转(我希望原点是形状的中心)。 任何提示将不胜感激。
var x = 50;
var y = 50;
var tranx;
var trany;
x -= tranx = x + shape.radius;
y -= trany = y + shape.radius;
elem.translate(tranx,trany);
elem.rotate(90 * radian);
var k = 0,
angle = 360/shape.sides;
elem.moveTo(x,y);
for (; k <shape.sides; k++) {
elem.lineTo(x+=Math.cos( ( angle * k )* radian) * shape.radius, y+=Math.sin( ( angle * k )* radian) * shape.radius);
}
最佳答案
我组合了几个函数来旋转正多边形。第一步是生成与 <canvas>
分开的 (x, y) 坐标列表。完全。需要注意的是,要获得相移(最终导致多边形旋转),您必须将旋转添加到余弦和正弦函数中的语句中:
Math.cos(rotation + (i * 2 * Math.PI / numberOfSides))
Math.sin(rotation + (i * 2 * Math.PI / numberOfSides))
以下是生成具有正多边形的 Canvas 并围绕其自身原点旋转多边形的工作示例:
var canvas = document.querySelector('canvas');
var polygon = {
sides: 3,
radius: 50,
phase: 0
};
document.addEventListener('click', function(e) {
switch (e.target.id) {
case "-side":
polygon.sides--;
break;
case "+side":
polygon.sides++;
break;
case "-phase":
polygon.phase -= Math.PI / 12;
break;
case "+phase":
polygon.phase += Math.PI / 12;
break;
}
drawPolygon(canvas, polygon.sides, polygon.radius, polygon.phase);
});
function generateCoordinates(centerX, centerY, numberOfSides, radius, rotation) {
var coordinates = [];
for (var i = 0; i < numberOfSides; i++) {
coordinates.push({
x: parseFloat((centerX + radius * Math.cos(rotation + (i * 2 * Math.PI / numberOfSides))).toFixed(4)),
y: parseFloat((centerY + radius * Math.sin(rotation + (i * 2 * Math.PI / numberOfSides))).toFixed(4))
})
}
return coordinates;
};
function drawPolygon(canvas, numberOfSides, radius, rotation) {
var context = canvas.getContext('2d');
canvas.height = radius * 2;
canvas.width = radius * 2;
var coordinates = generateCoordinates(radius, radius, numberOfSides, radius, rotation);
context.strokeStyle = "black";
context.beginPath();
coordinates.forEach(function(coordinate, index) {
if (index === 0) {
context.moveTo(coordinate.x, coordinate.y);
} else {
context.lineTo(coordinate.x, coordinate.y);
}
});
context.closePath();
context.stroke();
}
drawPolygon(canvas, polygon.sides, polygon.radius, polygon.phase);
<canvas></canvas>
<div>
<button id="-side">fewer sides</button>
<button id="+side">more sides</button>
</div>
<div>
<button id="-phase">minus phase shift</button>
<button id="+phase">plus phase shift</button>
</div>
关于javascript - 在 HTML Canvas 上旋转多边形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14712719/