围绕点画布旋转多边形 [英] Rotating a polygon around a point javascript canvas

查看:211
本文介绍了围绕点画布旋转多边形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码绘制多边形:

I draw a polygon using the following code:

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,然后旋转它,但它给出奇怪的结果。

However, the rotation is slightly off. How would I rotate it around the x and y? I tried to translate it to the cX and cY and then rotate it but it gives strange results.

推荐答案

strong>以下是一种在围绕其中心点旋转正多边形的方法:

Here's one way to rotate a regular polygon around its centerpoint:

提示:如果要转换到中心点, cX&计算x,y时使用cY。

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();        
}

body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }

<canvas id="canvas" width=300 height=300></canvas>

这篇关于围绕点画布旋转多边形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆