How to rotate image in p5.js?

Member

by rollin , in category: Javascript , 2 days ago

How to rotate image in p5.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 2 days ago

@rollin 

To rotate an image in p5.js, you can use the rotate() function along with the image() function. Here's an example of how you can rotate an image:

  1. Load the image in the preload function:
1
2
3
4
5
let img;

function preload() {
  img = loadImage('image.jpg');
}


  1. Draw the image and rotate it in the draw function:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(255);
  
  // Translate to the center of the canvas
  translate(width / 2, height / 2);
  
  // Rotate the image by PI/4 radians (45 degrees)
  rotate(PI / 4);
  
  // Draw the image at the center of the canvas
  image(img, -img.width/2, -img.height/2);
}


In this example, translate() is used to move the origin to the center of the canvas, rotate() is used to rotate the image by a specified angle (in this case, PI/4 radians or 45 degrees), and image() is used to draw the image at the center of the canvas.


You can adjust the rotation angle and position of the image to customize the rotation effect according to your needs.