我需要旋转图像,但我的代码没有围绕中心旋转,我不明白为什么。当我运行它时,我看不到它,所以我怀疑它是在屏幕外绘制的。
push();
rotate(PI / 2 * rotation);
imageMode(CENTER);
image(this.texture, centerPosX, centerPosY);
pop();
当我去掉
rotate
时,图片能够正常绘制,但是我需要将它旋转。我需要旋转图像,但我的代码没有围绕中心旋转,我不明白为什么。当我运行它时,我看不到它,所以我怀疑它是在屏幕外绘制的。
push();
rotate(PI / 2 * rotation);
imageMode(CENTER);
image(this.texture, centerPosX, centerPosY);
pop();
rotate
时,图片能够正常绘制,但是我需要将它旋转。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()函数,你可以传入与正常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解决同样的问题,并想出了一个简单的解决方案。基本上,您只需要将图像转换到您想要它出现的位置,然后在旋转之前必须处于imageMode(CENTER)模式。
push()
translate(xPosition, yPosition);
imageMode(CENTER);
rotate(imageRotation)
image(yourImage, 0, 0)
pop()
width
和height
是画布还是图片的尺寸? - FCin