Rotation and Translation
After the lab, you might want to read more on rotation and translation. Here are some links:
- p5js Transformations
- 2D Transformations – this is for Processing in Java, not p5js in Javascript, but the tutorial is good and should be understandable as long as you don’t try to copy the syntax exactly.
Let’s begin with a simple rectangle.
function setup() {
createCanvas(200, 200);
}
function draw() {
background(220);
rect(5, 5, 50, 50);
}
Rotation uses push(), pop(), rotate(), and radians()…
function setup() {
createCanvas(200, 200);
}
function draw() {
background(220);
push();
rotate(radians(10));
rect(5, 5, 50, 50);
pop();
}
We can modify this to change the angle every frame:
var angle = 0;
function setup() {
createCanvas(200, 200);
}
function draw() {
background(220);
push();
rotate(radians(angle));
rect(5, 5, 50, 50);
pop();
angle = angle + 5;
}
Now, what about rotating about some other point on the canvas? The trick is to translate — or shift the origin to a new location — and rotate about that point, draw the rotating object, and finally undo the translation (with pop();).
var angle = 0;
function setup() {
createCanvas(200, 200);
}
function draw() {
background(220);
push();
translate(100, 100);
rotate(radians(angle));
// note: now we draw the rectangle at 0,0:
rect(0, 0, 50, 50);
pop();
angle = angle + 5;
}
We can make the rectangle spin around its center by changing the mode to center the rectangle:
var angle = 0;
function setup() {
createCanvas(200, 200);
}
function draw() {
background(220);
fill(255); // control rect color explicitly
stroke(0);
push();
translate(100, 100);
rotate(radians(angle));
rectMode(CENTER); // center rect around 0,0
rect(0, 0, 50, 50);
pop();
angle = angle + 5;
}
Lab Work
- Copy the previous program (lab3spin3) into a sketch.js on your computer and test it to make sure you have a good starting point.
- Modify the program by moving
background(220);
to the end ofsetup()
. - Can you explain the result?
- Modify the program further so that the spinning box follows the mouse.
- SHOW YOUR PROGRAM AND OUTPUT TO YOUR TA BEFORE CONTINUING.
- Copy your
sketch.js
to a backup file just in case and continue. - Make a program to create the spiral shown below.
- SHOW YOUR PROGRAM AND OUTPUT TO YOUR TA BEFORE LEAVING.
- If you have extra time, stick around and help someone who is still working.
Your goal is to create this image.
Hints
- The image is created over time by repeatedly drawing a small black circle.
- There are two global variables:
angle
as in the examples above, and another variable to represent where to draw the circle. - Both variables increase by a small increment each time
draw()
is called. - You do not have to reproduce the image exactly, as long as you make a spiral.