Reputation: 67
I'm drawing some objects on canvas but if later I change the background image on demand, then already drawn objects are behind the background image. How to bring already drawn objects in front. Below is the sample code i'm using to change the background image.
function draw() { if(chnBg){ //if change background is clicked loadImage("images/Grid_Image.png",function(bg){
background(bg);
}); } }
Upvotes: 0
Views: 2082
Reputation: 42176
You could just store your state in a data structure of some kind and redraw everything each frame.
Another approach would be to draw your objects to a buffer graphics instead of directly to the canvas. Then draw the background to the canvas, and then draw the buffer to the canvas.
More info is available in the reference.
Upvotes: 0
Reputation: 32879
You will need to set globalCompositeOperation
to destination-over
before drawing / changing the background image ...
let canvas;
// setup
function setup() {
canvas = createCanvas(width, height);
}
// draw
function draw() {
if (chnBg) { //if change background is clicked
loadImage("images/Grid_Image.png", function(bg) {
canvas.drawingContext.globalCompositeOperation = 'destination-over'; //<-- set this
background(bg);
});
}
}
Upvotes: 1