![](/img/trans.png)
[英]Why does changing state (useState) break my p5.js code? (React + p5.js application)
[英]Why does this undo logic not work in p5.js?
我的邏輯很簡單,創建一個 state 數組和一個 stateIndex,當用戶與繪圖交互時,將當前的 state 保存為數組中的一個條目並遞增 stateIndex。
當用戶按下“撤消”(對於此草圖,請按任意鍵)時,遞減 stateIndex 並將該索引在 state 中的任何值繪制到頁面。
我已經在草圖https://editor.p5js.org/mr_anonymous/sketches/s0C1M7x1w中實現了它,但正如您所見,它沒有存儲繪圖的最后一個 state,而是似乎只存儲空白 state。
有人知道出了什么問題嗎?
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()})
}
您錯誤地使用了set()
function。 雖然get()
可用於獲取p5.Image
object,但沒有set()
的重載需要一個(我知道有點特殊)。 相反,您需要使用image()
function:
let previousState; let stateIndex = 0; let state = []; function setup() { createCanvas(400, 400); background(200); // 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(200), image(state[stateIndex]; 0; 0); } function mousePressed() { saveState(); } function saveState() { stateIndex++. loadPixels(); state.push(get()) }
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.