I’m having trouble making graphics objects after the sketch is already running. Is this not something I’m supposed to be able to do?
In this sketch, you can press the spacebar to create a blue square or you can press the A key to create a red one. You can press the same key again to destroy that square.
What I’m doing here is creating a graphics object on the first press of each of those keys and then calling the remove method on it. If you press it again, it creates another one and stores it in the same place the first one was stored in. It seems at first glace that it’s not making any subsequent squares after the first one you make, but actually, it does still create the graphics object and add it to the HTML, it’s just that subsequent drawing to it doesn’t seem to work anymore.
Am I doing something wrong? Considering that p5.Graphics doesn’t have a resize method, I figured destroying it and creating a new one was the only way to resize it, and I want to be able to do that in a project.
Any thoughts on this one? What I’m doing doesn’t seem to contradict any usage instructions as far as I can tell. Sorry about the self-reply bump, I dunno if that goes against any community standards, but it seemed like enough time went by that it was warranted.
It sounds like you’re trying to repeatedly show/hide an object by using keyboard input. For whatever it’s worth, my approach to this would be to create a display() method in my class and then toggle a boolean with the keyboard input. When it’s true use draw() to display() it, otherwise do nothing. The following is a simple example of this technique. You should see a red rectangle when the letter ‘a’ is entered on the canvas and then when you enter ‘a’ a second time it should disappear. The class is never changed.
let r;
let showRect = false;
function setup() {
createCanvas(500, 400);
r = new Rect();
}
function draw() {
background(220);
if(showRect == true){
r.display();
}
}
class Rect {
constructor() {
this.x = 100;
this.y = 100;
this.w = 200;
this.h = 100
}
display() {
fill(255, 0, 0);
rect(this.x, this.y, this.w, this.h);
}
}
function keyPressed() {
if (keyCode === 65) {
if(showRect == false){
showRect = true;
} else {
showRect = false;
}
}
}
I appreciate your helpful suggestion! But that’s not really what I’m trying to do. I’m trying to make P5.Graphics objects at runtime, and the sketch I have here is just a basic way to show that the means I figured I should use to do that doesn’t seem to work as expected. Of course, if I were just trying to hide and show objects, it would be a great deal easier.