Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 790
FCin Avatar asked Jul 29 '17 11:07

FCin


2 Answers

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>
like image 87
ɢʀᴜɴᴛ Avatar answered Oct 20 '22 05:10

ɢʀᴜɴᴛ


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);
}
like image 28
khi48 Avatar answered Oct 20 '22 07:10

khi48