p5js has a clear() function which clears everything from the screen. I want to keep the canvas created by createCanvas() but clear the createGraphics() one only. How can I do this ?
//something like this
var canvas2;
function setup() {
createCanvas(400, 400);
canvas2 = createGraphics(400,400);
canvas2.clear()
noLoop()
}
function draw() {
fill(255,0,0)
rect(60,60,40,40)
canvas2.fill(20,44,240);
canvas2.rect(20,20,40,40);
image(canvas2,0,0)
}
function mousePressed() {
//something which clears the createGraphics() canvas only and keeps the createCanvas() one
}
You can clear the content of a graphics object using its clear()
function. Here's an example:
var canvas2;
function setup() {
createCanvas(400, 400);
canvas2 = createGraphics(400,400);
canvas2.fill(20,44,240);
canvas2.rect(20,20,40,40);
}
function draw() {
background(255);
fill(255,0,0)
rect(60,60,40,40)
image(canvas2,0,0)
}
function mousePressed() {
canvas2.clear();
}
I moved the canvas2.rect(20, 20, 40, 40)
call to be inside the setup()
function, because otherwise you're redrawing to the canvas even after you clear it. I also removed your noLoop()
call so that you could see the result of clearing the canvas.