Learn

As we have seen in the previous exercise, the `rotate()` function on its own is not enough to rotate a shape around its center. When we `rotate()` an element, it often moves off the screen because the whole p5.js canvas is being rotated. In order to rotate a shape around its center, you first need to `translate()` the shape to be in the middle of the canvas.

``````// Move the origin to the center of the canvas
translate(width / 2, height / 2);``````

Then, you need to rotate your shape to the desired radian value. You can use the `radians()` function to convert the value passed to the `rotate()` function is in radians. In the example below, we use the p5.js `frameCount` variable to get the shape to rotate incrementally.

``````// Rotate by frameCount radians

Lastly, you need to draw the shape and set its origin point to be at the `CENTER` of the shape.

``````// Set the origin point to be the rectangle's center
rectMode(CENTER);
rect (0, 0, 1, height); ``````

In order to rotate a shape around its top-left corner, you can set the mode to `CORNER` instead of `CENTER`. Since `CORNER` is the default origin point for drawing rectangles, you don’t need to explicitly call the `rectMode()` function. The two code examples below would produce the same result—a rectangle rotating around its top-left corner.

``````// Rotates from rectangle's top-left corner
rectMode(CORNER);
rect (0, 0, 1, height);

// Also rotates from rectangle's top-left corner because rectMode() is CORNER by default
rect (0, 0, 1, height); ``````

The diagram below shows the difference between rotating a shape with a `CORNER` versus a `CENTER` origin point. Remember that the values for the transformation functions are accumulative. For example, the values passed into the first `rotate()` function will be added to any of the `rotate()` functions that are called afterward.

### Instructions

1.

Below the `fill()` function, specify the origin points of the rectangles to be the `CENTER`.

2.

After the `rectMode()` function, translate the rectangles `width / 2` to the right and `height / 2` to the bottom. This will move your rectangles to the center of the canvas.

3.

Below the `translate()` function, rotate your rectangles by a quarter pi (π).

4.

Rotate the second rectangle by `frameCount / 2` in radians. Remember that you can convert a value to be in radians using the `radians()` function.

Now you should see the rectangle with a blue outline rotating from its center!