如何在 p5.js 中旋转图像

How to rotate image in p5.js

我需要旋转图像,但我的代码没有围绕中心旋转图像,我不明白为什么。当我 运行 它时我看不到它,所以我怀疑它把它画在了屏幕之外。

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

当我删除 rotate 时,它可以正确绘制图像,但我需要旋转它。

您需要将 canvas 原点平移到中心或 canvas 内的任何点(您希望成为 旋转中心 ),旋转前。

这可以使用 translate() 方法完成。

ᴅᴇᴍᴏ

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>

制作了一个功能,可以在其他人感到懒惰时旋转图像。

使用 rotate_and_draw_image() 您应该能够传递与普通图像 () 相同的信息,但具有以度数定义的额外旋转值。 (图像的位置定义为左上角(与默认相同),因此无需更改任何内容)。

有点低效,但应该很容易实施。希望看到任何改进。

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);
}

所以这个线程有点旧,但我试图用 p5.js 解决同样的问题并提出了简单的解决方案。基本上你只需要对你希望图像出现在你的 push / pop 中的位置进行转换,你还需要在旋转之前处于 imageMode(CENTER) 状态。

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