在 p5.js 中制作较小版本的画布和对象
2021-04-30
796
因此,我尝试在 p5.js 中制作画布和精灵的精确小比例版本,并将其放入一个框中。是否有函数或方法可以做到这一点?精灵的背景、颜色和图像应该相同。
2个回答
有两种方法可以实现这一点,一种方法是将所有内容绘制到
p5.Graphics
缓冲区,然后将该缓冲区绘制到主画布上两次,目标大小不同。另一种方法是将主要绘制部分直接绘制到画布上,然后使用
pixels
数组根据画布内容创建
p5.Image
,然后使用
image
函数将其绘制到画布上。
示例 1.
p5.Graphics
let graphics;
function setup() {
createCanvas(windowWidth * 0.9, windowHeight * 0.9);
graphics = createGraphics(width, height);
graphics.background(100);
}
function draw() {
graphics.ellipse(mouseX, mouseY, 50, 50);
image(graphics, 0, 0, width, height, 0, 0, graphics.width, graphics.height);
// Draw picture in picture
let aspect = width / height;
image(graphics, 10, 10, 100, 100 / aspect, 0, 0, graphics.width, graphics.height);
push();
noFill();
strokeWeight(3);
rect(10, 10, 100, 100 / aspect);
pop();
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>
</head>
<body>
</body>
</html>
示例 2. 像素和图像
注意:此选项的缺点是更复杂、速度更慢,并且它不支持持久绘制的内容以及
p5.Graphics
选项,因为它会在后续帧中显示自身。
let img;
let density;
function setup() {
createCanvas(round(windowWidth * 0.9), round(windowHeight * 0.9));
density = pixelDensity();
img = createImage(width, height);
img.loadPixels();
background(100);
}
function draw() {
ellipse(mouseX, mouseY, 30, 30);
loadPixels();
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
let srcPixel = y * 4 * width * density ** 2 + x * 4 * density;
let dstPixel = y * 4 * img.width + x * 4;
for (let channel = 0; channel < 4; channel++) {
img.pixels[dstPixel + channel] = pixels[srcPixel + channel];
}
}
}
img.updatePixels();
// Draw picture in picture
let aspect = width / height;
image(img, 10, 10, 100, 100 / aspect, 0, 0, img.width, img.height);
push();
noFill();
strokeWeight(3);
rect(10, 10, 100, 100 / aspect);
pop();
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>
</head>
<body>
</body>
</html>
Paul Wheeler
2021-04-30
我不知道 p5.play 是如何工作的,但我猜测
copy()
命令(
reference
)可以满足您的要求。要将小地图放在下角,您可以执行以下操作:
function draw() {
//whatever is currently in your draw loop...
let minimapWidth = 50;
let minimapHeight = 50;
copy(0, 0, width, height,
width-minimapWidth,
height-minimapHeight,
minimapWidth, minimapHeight
);
}
Jacob Stuligross
2021-04-30