我使用以下代码绘制多边形:
drawPolygon = function(context, cX, cY, radius, sides) {
if (sides< 3)
return;
context.save();
var anglePerSegment = Math.PI * 2 / sides;
for (var i = 0; i <= sides; i++) {
var angle = anglePerSegment * i;
var x = cX+ radius * Math.cos(angle);
var y = cY+ radius * Math.sin(angle);
if (i == 0) {
context.moveTo(x, y);
} else {
context.lineTo(x, y);
}
}
context.fill();
context.restore();
}
然而,旋转稍微偏离。我如何围绕x和y旋转它? 我试图将它转换为cX和cY,然后旋转它,但它会产生奇怪的结果。
答案 0 :(得分:2)
以下是围绕其中心点旋转正多边形的一种方法:
提示:如果你想转换到中心点,那么请关闭cX&amp; cY计算x,y时。
currentTab: this.flux.store.tabStore.getCurrentTab()
&#13;
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var sideCount=6;
var size=100;
var centerX=cw/2;
var centerY=ch/2;
var strokeWidth=4;
var strokeColor='gray';
var fillColor='skyblue';
var rotationDegrees=0;
requestAnimationFrame(animate);
function animate(time){
ctx.clearRect(0,0,cw,ch);
drawPolygon(sideCount,size,centerX,centerY,strokeWidth,strokeColor,fillColor,rotationDegrees)
rotationDegrees+=360/120;
requestAnimationFrame(animate);
}
function drawPolygon(sideCount,size,centerX,centerY,strokeWidth,strokeColor,fillColor,rotationDegrees){
var radians=rotationDegrees*Math.PI/180;
ctx.save();
ctx.translate(centerX,centerY);
ctx.rotate(radians);
ctx.beginPath();
ctx.moveTo (size * Math.cos(0), size * Math.sin(0));
for (var i = 1; i <= sideCount;i += 1) {
ctx.lineTo (size * Math.cos(i * 2 * Math.PI / sideCount),size * Math.sin(i * 2 * Math.PI / sideCount));
}
ctx.fillStyle=fillColor;
ctx.strokeStyle = strokeColor;
ctx.lineWidth = strokeWidth;
ctx.stroke();
ctx.fill();
ctx.restore();
}
&#13;
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
&#13;