添加矩形并旋转它们

adding rectangles and rotate them

本文关键字:旋转 添加      更新时间:2023-09-26

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

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

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

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];

代码继续,但这位给了我这个错误: 未捕获的类型错误: 无法读取未定义的属性"100"

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

第二个位 im 有问题正在旋转它们,im 使用以下函数:

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

 }

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

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

如果修改我的整个代码会让它更容易,请告诉我提供它。感谢您抽出宝贵时间,对不起这个长话题。

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

此代码将:

  • 绘制一个 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();