Javascript多边形旋转

时间:2015-02-02 19:39:32

标签: javascript canvas

所以这是我的代码

var numberOfSides,
    angle = 0.2,
    num = 8,
    size = 100;

numberOfSides = prompt("How many sides would you like on your polygon");

c.translate( 300,300);
if (numberOfSides > 0) {    
    c.beginPath();
    //for (var j = 0 ; j < num ; j ++ ){    
    c.lineTo(size * Math.cos(0),size * Math.sin(0));
    for (var j = 0 ; j < num ; j ++ ){  
        for (var i = 0; i <= numberOfSides; i ++) {
            c.lineTo(size * Math.cos(i * 2 * Math.PI / numberOfSides), size * Math.sin(i * 2 * Math.PI / numberOfSides));
    }
        c.rotate(angle);
    }

    c.strokeStyle = "#FF0000";
    c.lineWidth = 2;
    c.stroke();
    c.fillStyle = "#FF0000";
}

我遇到的问题是在我的多边形的右下角有线条......任何人都可以帮我这个

1 个答案:

答案 0 :(得分:0)

以下是绘制旋转的正多边形的方法:

function drawPolygon(centerX,centerY,theAngle,sides){

    // save the untranslated & unrotated context state
    c.save();

    // translate and rotate the canvas
    c.translate(centerX,centerY);
    c.rotate(theAngle);

    // draw the regular polygon
    c.beginPath();
    c.lineTo(size * Math.cos(0),size * Math.sin(0));
    for (var i = 0; i <= sides; i ++) {
        c.lineTo(size * Math.cos(i * 2 * Math.PI / sides), size * Math.sin(i * 2 * Math.PI / sides));
    }
    c.stroke();

    // restore the context to its untranslated & unrotated state
    c.restore();    
}

以下是示例代码和动画演示:

var canvas=document.getElementById("canvas");
var c=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var numberOfSides=5,
    angle = 0.2,
    angleChange=Math.PI/60;
num = 8,
  size = 40;

c.strokeStyle = "#FF0000";
c.lineWidth = 2;
c.fillStyle = "#FF0000";


if (numberOfSides > 0) {    
  requestAnimationFrame(animate);
}

function animate(time){
  requestAnimationFrame(animate);
  c.clearRect(0,0,canvas.width,canvas.height);
  drawPolygon(150,150,angle,numberOfSides);
  angle+=angleChange;
}


function drawPolygon(centerX,centerY,theAngle,sides){

  // save the untranslated & unrotated context state
  c.save();

  // translate and rotate the canvas
  c.translate(centerX,centerY);
  c.rotate(theAngle);

  // draw the regular polygon
  c.beginPath();
  c.lineTo(size * Math.cos(0),size * Math.sin(0));
  for (var i = 0; i <= sides; i ++) {
    c.lineTo(size * Math.cos(i * 2 * Math.PI / sides), size * Math.sin(i * 2 * Math.PI / sides));
  }
  c.stroke();

  // restore the context to its untranslated & unrotated state
  c.restore();    
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>