Amer Almutawa
Amer Almutawa

Reputation: 15

adding rectangles and rotate them

Im trying to write a program to generate random rectangles within a tag, and then rotate each rectangle within its origin, if I hit the start button again the canvas should clear out to draw a new set of rectangles and rotate them and so on.

pasting my whole program would look hideous, so Ill post what I think is important:

Creating my arrays and initializing some values :

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

the code goes on but this bit gives me this error: Uncaught TypeError: Cannot read property '100' of undefined

im trying to create an array for each point, origin x and y + width and height. then using the fillRect ill pass the array values to draw my rectangles.

Second bit im having problem with is rotating them, im using the following function:

 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 calling it in the following function but it does nothing, althought later I need to locate each rect origin and rotate it in the right way but for now I just want to make sure the function works :

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

 }

if revising my whole code will make it easier, do let me know to provide it. thank you for your time and sorry for the long topic.

Upvotes: 0

Views: 117

Answers (1)

markE
markE

Reputation: 105015

Here's some code to get you started...

This code will:

  • Draw a 50x30 rectangle,
  • That is rotated 30 degrees around its centerpoint,
  • And is positioned with its centerpoint at canvas coordinate [100,100]

The code:

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

Upvotes: 1

Related Questions