How to rotate image in p5.js

FCin picture FCin · Jul 29, 2017 · Viewed 7.5k times · Source

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.

Answer

ɢʀᴜɴᴛ picture ɢʀᴜɴᴛ · Jul 29, 2017

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>