FCin
FCin

Reputation: 3925

How to rotate image in p5.js

I need to rotate image, but my code doesn't rotate it around center and I don't understand why. When I run it I cannot see it, so I suspect it draws it outside of screen.

push();
rotate(PI / 2 * rotation);
imageMode(CENTER);
image(this.texture, centerPosX, centerPosY);
pop();

When I remove rotate, it draws the image properly, but I need to rotate it.

Upvotes: 7

Views: 18174

Answers (3)

arcticnerd
arcticnerd

Reputation: 11

So this thread is a little old but I was trying to solve the same problem with p5.js and came up with easy solution. Basically you just need to do a translation to the position that you want the image to appear at inside your push / pop, also you need to be in imageMode(CENTER) before you rotate.

push()
translate(xPosition, yPosition);
imageMode(CENTER);
rotate(imageRotation)
image(yourImage, 0, 0)
pop()

Upvotes: 0

khi48
khi48

Reputation: 51

made a function to rotate an image if anyone else is feeling lazy.

Using the rotate_and_draw_image() you should be able to pass in the same information as you would to a normal image(), but with an extra rotation value defined in degrees. (The position of the image is defined as the top left (same as default) so nothing should need to be changed).

Kind of an inefficient process, but should be easy to implement. Would be kee to see any improvements.

var img;
var angle = 0;
var x = 0;
var y = 0;

function setup() {
   createCanvas(displayWidth, 725);
   img = loadImage('fly2.png');
}

function rotate_and_draw_image(img_x, img_y, img_width, img_height, img_angle){
  imageMode(CENTER);
  translate(img_x+img_width/2, img_y+img_width/2);
  rotate(PI/180*angle);
  image(img, 0, 0, img_width, img_height);
  rotate(-PI / 180 * img_angle);
  translate(-(img_x+img_width/2), -(img_y+img_width/2));
  imageMode(CORNER);
}

function draw() {
  background(255);

  // this image stays still in top left corner
  image(img, 0, 0, 150, 150);

  angle += 0.5;

  x+=1;
  if (x >width){
    x = 0;
  } 

  y -=1;
  if (y < 0){
    y = height;
  } 

  // moves image to desired location (defining top left corner), 
  // rotates and draws image.
  rotate_and_draw_image(x, y, 150, 150, angle);


  // this image also stays constant in bottom right corner
  image(img, width-150, height-150, 150, 150);
}

Upvotes: 5

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32889

You need to translate the canvas origin to center or any point within the canvas (that you wish to make the center of rotation), before rotating.

This could be done using translate() method.

ᴅᴇᴍᴏ

var img;

function setup() {
   createCanvas(300, 300);
   img = loadImage('https://i.imgur.com/Q6aZlme.jpg');
}

function draw() {
   background('#111');
   translate(width / 2, height / 2);
   rotate(PI / 180 * 45);
   imageMode(CENTER);
   image(img, 0, 0, 150, 150);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.10/p5.min.js"></script>

Upvotes: 9

Related Questions