为什么这个撤消逻辑在 p5.js 中不起作用?
我的逻辑很简单,创建一个状态数组和一个stateIndex,当用户与绘图交互时,将当前状态保存为数组中的条目并递增stateIndex。
当用户按下“撤消”时(对于此草图,请按任意键),递减 stateIndex 并将该索引的状态值绘制到页面。
我已经在此草图中实现了它 https://editor.p5js.org/mr_anonymous/sketches/ s0C1M7x1w 但正如您所看到的,它似乎只存储空白状态,而不是存储绘图的最后状态。
有人知道出了什么问题吗?
let previousState;
let stateIndex = 0;
let state = [];
function setup() {
createCanvas(400, 400);
background(255);
// save state at beginning for blank canvas
saveState();
}
function draw() {
if (mouseIsPressed) {
fill(0, 0, 0);
circle(mouseX, mouseY, 20);
}
}
function keyPressed(e) {
undoToPreviousState();
}
function undoToPreviousState() {
if (!state || !state.length || stateIndex === 0) {
return;
}
stateIndex --;
background(255);
set(state[stateIndex], 0, 0);
}
function mousePressed() {
saveState();
}
function saveState() {
stateIndex ++;
loadPixels();
state.push({...get()})
}
My logic is simple, create a state array and a stateIndex, when the user interacts with the drawing, save the current state as an entry in the array and increment the stateIndex.
When the user presses "undo" (for this sketch press any key), decrement the stateIndex and draw to the page whatever value is in state for that index.
I've implemented it in this sketch https://editor.p5js.org/mr_anonymous/sketches/s0C1M7x1w but as you can see instead of storing the last state of the drawing it seems to only store the blank state.
Anyone know what's going wrong?
let previousState;
let stateIndex = 0;
let state = [];
function setup() {
createCanvas(400, 400);
background(255);
// save state at beginning for blank canvas
saveState();
}
function draw() {
if (mouseIsPressed) {
fill(0, 0, 0);
circle(mouseX, mouseY, 20);
}
}
function keyPressed(e) {
undoToPreviousState();
}
function undoToPreviousState() {
if (!state || !state.length || stateIndex === 0) {
return;
}
stateIndex --;
background(255);
set(state[stateIndex], 0, 0);
}
function mousePressed() {
saveState();
}
function saveState() {
stateIndex ++;
loadPixels();
state.push({...get()})
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您错误地使用了
set()
函数。虽然get()
可用于获取p5.Image
对象,但set()
不存在需要 1 的重载(有点我知道,很特殊)。相反,您需要使用image()
函数:You're using the
set()
function incorrectly. Whileget()
can be used to get ap5.Image
object, there is no overload ofset()
that takes one (a bit idiosyncratic, I know). Instead you'll want to use theimage()
function: