Javascript 添加矩形并旋转它们

Javascript 添加矩形并旋转它们,javascript,html5-canvas,Javascript,Html5 Canvas,我想写一个程序,在标签中生成随机矩形, 然后在其原点内旋转每个矩形,如果我再次点击开始按钮,画布将清空以绘制一组新的矩形并旋转它们,依此类推 粘贴我的整个程序看起来很可怕,所以我会发布我认为重要的内容: 创建我的数组并初始化一些值: var rectArrayStartX,rectArrayStartY,rectArrayDimY, rectArrayDimX; function start() { if (i >= 1){ canvas.restore() i--;

我想写一个程序,在标签中生成随机矩形, 然后在其原点内旋转每个矩形,如果我再次点击开始按钮,画布将清空以绘制一组新的矩形并旋转它们,依此类推

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

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

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];
我在下面的函数中调用它,但它不起任何作用,尽管稍后我需要定位每个rect原点并以正确的方式旋转它,但现在我只想确保该函数正常工作:

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

 }
如果修改我的全部代码将使它更容易,请务必让我知道如何提供它。
谢谢您的时间,很抱歉话题太长。

这里有一些代码可以帮助您开始

该代码将:

  • 画一个50x30的矩形
  • 围绕其中心点旋转30度
  • 并将其中心点定位在画布坐标[100100]
守则:

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

阅读本主题后的一些想法:我们不可能从您提供的内容中完全解决您的问题。确保
i
是一个全局变量。在声明变量时,尝试通过初始化来修复所遇到的错误。试着用伪代码简化你的程序,这会有很大帮助
// 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();