0

我试图编写一个程序来在标签内生成随机矩形,然后在其原点内旋转每个矩形,如果我再次点击开始按钮,画布应该清除以绘制一组新的矩形并旋转它们等等。

粘贴我的整个程序看起来很可怕,所以我会发布我认为重要的内容:

创建我的数组并初始化一些值:

var rectArrayStartX,rectArrayStartY,rectArrayDimY,   rectArrayDimX;

function start()
{
   if (i >= 1){
  canvas.restore()
  i--;
}
construct();
window.setInterval( "rotateShape()", 500 );

}

function construct()
{

if ( i < 1) {
  canvas.save();
  i++
}
var canvas = document.getElementById("gameId");
var context = canvas.getContext("2d");
var k,m;

var points = parseInt(pGame.box.value);
rectArrayStartX[100];
rectArrayStartY[100];
rectArrayDimY[100];
rectArrayDimX[100];

代码继续,但这一位给了我这个错误: Uncaught TypeError: Cannot read property '100' of undefined

我试图为每个点、原点 x 和 y + 宽度和高度创建一个数组。然后使用 fillRect 传递数组值来绘制我的矩形。

我遇到的第二个问题是旋转它们,我使用以下功能:

 function rotateShape()
 {
  var randomAngle;
  randomAngle = Math.random() * 5 ;
        if (randomAngle>3.14)
        {
              randomAngle=3.14
        }
 //context.translate(canvas.width / 2, canvas.height / 2);
  context.rotate(randomAngle);


 }

我在下面的函数中调用它,但它什么也没做,虽然稍后我需要找到每个矩形原点并以正确的方式旋转它,但现在我只想确保函数有效:

 function start()
 {
   if (i >= 1){
   canvas.restore()
   i--;
 }
 construct();
  window.setInterval( "rotateShape()", 500 );

 }

如果修改我的整个代码会使它更容易,请让我知道提供它。感谢您抽出宝贵的时间,并对冗长的话题感到抱歉。

4

1 回答 1

1

这里有一些代码可以帮助您入门...

此代码将:

  • 绘制一个 50x30 的矩形,
  • 即围绕其中心点旋转 30 度,
  • 并且其中心点位于画布坐标 [100,100]

编码:

// save the untransformed context state

context.save();

// move (translate) to the "rotation point" of the rect
// this will be the centerpoint of the rect

context.translate(100,100);

// rotate by 30 degrees
// rotation requires radians so a conversion is required

context.rotate( 30*Math.PI/180 );

// draw a 50 x 30 rectangle
// since rects are positioned by their top-left
// and since we're rotating from the rects centerpoint
// we must draw the rect offset by -width/2 and -height/2

var width=50;
var height=30;

context.fillRect( -width/2, -height/2, width, height );

// restore the context to its untransformed state

context.restore();
于 2013-10-30T14:09:09.470 回答