translate and rotate

translate(x,y) is a p5.js function which takes two parameters.

The value of the x parameter specifies left/right translation, whereas the y parameter specifies up/down translation. 

After calling this function, all the elements placed after this will behave according to the specified parameters.

In order to apply the translate only to specific elements, we can use the push() and pop() .

rotate() is a p5.js function which rotates an element. The amount at which the element will be rotated depends on the number specified inside the parenthesis. The angles can be given in either degrees or radians

Example 

Here is an example code which uses translate and rotate to create a rectangle which will be rotating clockwise: 

// initialize the angle
let theta = 0;
function setup() {
  createCanvas(windowWidth, windowHeight);
  background(50);
}
function draw() {
  // move the origin to the center of the canvas
  translate(width / 2, height / 2);
  rotate(radians(theta));
  // draw the rect in relation with the origin
  // in this case the x pos will be (width/2-15) and the y position (height/2-85)
  rect(-15, -85, 30, 100);
  // increment the angle by one degree
  theta += 1;
}


You can see the result of the above code here

Exercise

  1. Open your Visual Studio editor and the p5yourName folder.
  2. Open the file ex812.js in your editor and save it as ex924.js
  3. Open the file ex812.html in your editor and save it as ex924.html
  4. In the ex924.html file, update the link to ex924.js  from exersice812.js
  5. Go to the index.html file and create, under Module 9, a link to the ex924.html  file with the title "translate and rotate".

Modify the ex924.jsfile to create and use the above example as a base to create a clock simulation. The clock will only show hours and minutes. The hours "hand" should move with 1/12 the speed of minutes "hand". Use push(),pop(),translate and rotate to create your clock. You can see here an example.

Answer:

// initialize the angle
let theta = 0;
function setup() {
  createCanvas(windowWidth, windowHeight);
  background(50);
}
function draw() {
  push();
  // move the origin to the center of the canvas
  translate(width / 2, height / 2);
  // move the hour hand ( move 1/12th the speed of the minute hand )
  rotate(radians(theta / 12));
  rect(-15, -85, 30, 100);
  pop();
  push();
  // move the origin back to the center of the canvas
  translate(width / 2, height / 2);
  // move the minute hand
  rotate(radians(theta));
  rect(-10, -190, 20, 200);
  pop();
  // increment the angle by one degree
  theta += 1;
}

Do a Git commit with the message "translate and rotate".