У меня простой вопрос. В p5.js есть функция рисования. Я думаю, вы можете рисовать только элементы (например, прямоугольник изнутри этой функции). Я хочу нарисовать один прямоугольник во время функции, которая находится за пределами рисования. (запускается только при определенных событиях). Кто-нибудь знает, как я могу это сделать?
Обновлено: пробовал просто рисовать снаружи с помощью rect (x, y, w, h) не работает
также пробовали создать this.drawRect = function () {} внутри draw (), тоже не повезло



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


TL; DR: https://jsbin.com/widinuruna/edit?html,css,js,output
function setup() {
createCanvas(400, 400);
noLoop() // make draw to only be called once
}
function draw() { // usually called 60 times / s
background(220); // clears the canvas (including your rect, if drawn before)
}
setTimeout(()=> {
rect(20,20,50,50)
}, 300)
Вероятно, ваш прямоугольник был нарисован до того, как вы его увидели :)
ссылка: https://p5js.org/reference/#/p5/draw
Допустим, вам нужно нарисовать прямоугольник под курсором при нажатии мыши. В зависимости от вашего варианта использования вы можете:
перерисовывать все непрерывно
// try changing 60 to eg. 1, and click fast while moving the cursor
// - you'll see it will still only update once a second
function setup() {
createCanvas(400, 400)
frameRate(60) // make draw be called 60 times/s (default?)
}
// keeping "state" as an object is a common practice...
const state = {x: 0, y: 0} // initialize state
// ...then it can be updated whenever, eg. on interaction,
// without caring about the drawing
function mousePressed() {
// update state on interaction
state.x = mouseX; state.y = mouseY
}
// ...the screen will then update independently
function draw() {
// (avoid changing the state here)
background(220) // clear the canvas
rect(state.x, state.y, 50, 50) // draw according to state
}
// by separating "logic" (eg. changing the state) and drawing:
// - a "game" will "behave" the same even at different fps,
// important for multiplayer etc.
// - code will be simpler to reason about and work with, etc
перерисовывать только при необходимости
// using noLoop() in setup, draw() will only be called once initially
// then, either use rect in eg. mousePressed, or:
// keep using state, but manually call redraw() after changing the state
pros = "more efficient if less redraws then eg. 60fps is needed"
cons = "need to know when to invoke redraw,"
+ "possibly makes code a bit more complicated"
перерисуй только то, что нужно
// using either point 1 or 2, but in addition keeps track of the
// previous state, then, only redraws the part of the screen necessary
// eg. instead of calling background(200), which is the same as:
fill(200); rect(0,0,width,hight); fill(255) // to clear the screen (and restore fill color)
fill(200); rect(oldState.x,oldState.y,50,50); fill(255) // clearing only what was previously drawn
/* followed by */ rect(state.x,state.y,50,50); // as normal
// (assumes noStroke() is called in setup)
pros = "possibly much more efficient if large canvas"
cons = "possibly more complicated"