将 canvas 复制到 p5.js 中的图形对象
Copy canvas to graphics object in p5.js
我没能找到参考或解决这个问题,但我很好奇是否有办法在 p5.js 中获取绘制的 canvas 的当前状态并保存它到一个图形对象。
基本上,我在 setup
函数中做了很多预绘图,并想对其进行快照以用作 draw
函数中的背景。
我意识到我可以通过添加额外的图形对象为我的 setup
绘图添加额外的复杂层,但是将当前状态转换为新的 object/image 会容易得多(我有一个相当复杂的图形对象链,它们被放到主 canvas 上)。
我相信您正在寻找的是 copy()
函数。它可用于复制 canvas、p5.Graphics
对象和 p5.Image
对象内部和之间的像素区域。从主 canvas 复制到 p5.Image
时要注意的一件事是主 canvas 的像素密度取决于显示器(即高 DPI 的密度为 2显示),但 p5.Image
个对象没有密度。因此,对于高 DPI 显示,您的 p5.Image
对象需要超大。因此,我认为最好使用 p5.Graphics
。这是一个简单的例子:
let buffer;
function setup() {
let canvas = createCanvas(windowWidth, windowHeight);
background(100);
buffer = createGraphics(width, height);
let saveButton = createButton("save");
saveButton.position(20, 20);
saveButton.mouseClicked(() => {
// Copy from canvas into buffer
buffer.copy(
// source
canvas,
// source x, y, w, h
0, 0, width, height,
// destination x, y, w, h
0, 0, buffer.width, buffer.height)
});
let restoreButton = createButton("restore");
restoreButton.position(80, 20);
restoreButton.mouseClicked(() => {
// Copy from buffer into the canvas
copy(buffer, 0, 0, buffer.width, buffer.height, 0, 0, width, height);
});
}
function draw() {
circle(mouseX, mouseY, 20);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
我没能找到参考或解决这个问题,但我很好奇是否有办法在 p5.js 中获取绘制的 canvas 的当前状态并保存它到一个图形对象。
基本上,我在 setup
函数中做了很多预绘图,并想对其进行快照以用作 draw
函数中的背景。
我意识到我可以通过添加额外的图形对象为我的 setup
绘图添加额外的复杂层,但是将当前状态转换为新的 object/image 会容易得多(我有一个相当复杂的图形对象链,它们被放到主 canvas 上)。
我相信您正在寻找的是 copy()
函数。它可用于复制 canvas、p5.Graphics
对象和 p5.Image
对象内部和之间的像素区域。从主 canvas 复制到 p5.Image
时要注意的一件事是主 canvas 的像素密度取决于显示器(即高 DPI 的密度为 2显示),但 p5.Image
个对象没有密度。因此,对于高 DPI 显示,您的 p5.Image
对象需要超大。因此,我认为最好使用 p5.Graphics
。这是一个简单的例子:
let buffer;
function setup() {
let canvas = createCanvas(windowWidth, windowHeight);
background(100);
buffer = createGraphics(width, height);
let saveButton = createButton("save");
saveButton.position(20, 20);
saveButton.mouseClicked(() => {
// Copy from canvas into buffer
buffer.copy(
// source
canvas,
// source x, y, w, h
0, 0, width, height,
// destination x, y, w, h
0, 0, buffer.width, buffer.height)
});
let restoreButton = createButton("restore");
restoreButton.position(80, 20);
restoreButton.mouseClicked(() => {
// Copy from buffer into the canvas
copy(buffer, 0, 0, buffer.width, buffer.height, 0, 0, width, height);
});
}
function draw() {
circle(mouseX, mouseY, 20);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>