Rotating an element in p5.js means rotating the canvas from its top-left corner at (0, 0). Therefore, all the elements drawn on the coordinate system rotates together with the canvas.
The diagram below shows that the coordinate system is being rotated, along with the rectangle drawn on the canvas. The red rectangle shows the original location, while the gray rectangle shows its positions when rotated. Notice how the gray square goes off the canvas. This happens because the shape is situated on the rotating p5.js coordinate system.
You can rotate the canvas using the
rotate() function takes one argument—the angle of rotation represented by the
angle variable in the above code. By default, the angle of rotation is interpreted as a radian value—a unit of measuring angles. A single rotation, or a full circle, has 360° in degrees or 2π (6.28) in radians. A half rotation has a 180° in degrees or π (3.14) in radians.
p5.js provides representations of pi (π) values, which you can use by spelling out the words like below:
- π =
- π / 2 =
- π / 4 =
- 2 π =
The code below shows how you would pass in the
TWO_PI value to the
You can also convert a degree value into a radian value by calling the
radians() function. For example,
radians(180) would equate to
3.14, the equivalent to one π. It is possible to use the
radians() function inside the
Alternatively, you can specify the unit of measurement of angles by calling the
angleMode() function. Similar to how you set the
ellipseMode() to change the shape’s origin, the
angleMode() determines if the value inside the
rotate() function is interpreted as either degrees or radians.
You can set the mode to
DEGREES by writing:
You can also specify the mode to be
RADIANS, but keep in mind that the default mode for angles and the
rotate() function is already
fill() function, rotate the canvas by a quarter pi (π).
rotate() function you just wrote, specify the angle mode to be
Notice how changing the angle mode to degrees, alters the rotation amount of the elements.
angleMode() function , rotate the ellipses’
for loop by 30 degrees.
Right above the second
for loop, rotate the rectangle pattern by
frameCount * 10 radians.
Be sure to use the
radians() function to convert the value into radians.