How to rotate a rectangle shape from a specific point in p5.js?

by raven_corwin , in category: Javascript , 3 months ago

How to rotate a rectangle shape from a specific point in p5.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 3 months ago

@raven_corwin 

To rotate a rectangle shape from a specific point in p5.js, you can use the translate() and rotate() functions to set the pivot point before drawing the rectangle. Here is an example code snippet that demonstrates how to rotate a rectangle from a specific point:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
let angle = 0;
let rotatePointX = 100;
let rotatePointY = 100;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  
  // Set the pivot point for rotation
  translate(rotatePointX, rotatePointY);
  
  // Rotate the rectangle
  rotate(radians(angle));
  
  // Draw the rectangle
  rectMode(CENTER);
  rect(0, 0, 100, 50);
  
  // Increase the angle for rotation
  angle += 1;
}


In this code, the translate() function sets the pivot point for rotation at coordinates (rotatePointX, rotatePointY). The rotate() function is then used to rotate the rectangle by a specified angle in radians. Finally, the rectangle is drawn using the rect() function with the pivot point as the center. The angle variable is incremented in every frame to create a rotating effect.


You can adjust the rotatePointX, rotatePointY, and angle values to rotate the rectangle from a different point and at a different speed.