1

The following code makes use of the p5dom add-on to position the canvas in the centre of the window. To dynamically resize the canvas I'm using the windowResized() function. I want to keep the background function in setup. How do I prevent the background colour from clearing when I resize the window? Many thanks.

var cnv;

function centerCanvas() {
  var x = (windowWidth - width) / 2;
  var y = (windowHeight - height) / 2;
  cnv.position(x, y);
}

function setup() {
  cnv = createCanvas(windowWidth,windowHeight);
  centerCanvas();
  background(255, 0, 200);
}

function draw(){

}

function windowResized() {
  centerCanvas();
  resizeCanvas(windowWidth,windowHeight)
}
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
James
  • 1,355
  • 3
  • 14
  • 38

4 Answers4

1

One thing you might do is draw everything to a buffer instead of directly to the screen. The createGraphics() function is your friend here. From the P5.js reference:

var pg;
function setup() {
  createCanvas(100, 100);
  pg = createGraphics(100, 100);
}
function draw() {
  background(200);
  pg.background(100);
  pg.noStroke();
  pg.ellipse(pg.width/2, pg.height/2, 50, 50);
  image(pg, 50, 50);
  image(pg, 0, 0, 50, 50);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.16/p5.js"></script>

You would want to draw everything to a buffer, and then when the screen is resized, redraw that buffer.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
1

Simply by adding the background function to the draw one too.

Try this:

var cnv;

function centerCanvas() {
  var x = (windowWidth - width) / 2;
  var y = (windowHeight - height) / 2;
  cnv.position(x, y);
}

function setup() {
  cnv = createCanvas(windowWidth,windowHeight);
  centerCanvas();
  background(255, 0, 200);
}

function draw(){
  //HERE:
  background(255, 0, 200);
}

function windowResized() {
  //(you can add it here too...)
  centerCanvas();
  resizeCanvas(windowWidth,windowHeight);
}
MercyDude
  • 884
  • 10
  • 27
0

For an alternative method, you could use CSS to edit the dimensions using something similar to the following:

<style>
    canvas {
      width: 100%;
      height: 100%;
    }
</style>
Cobain Ambrose
  • 91
  • 1
  • 1
  • 8
0

I would simply set the background in the windowResized function.

function windowResized() {
  centerCanvas();
  resizeCanvas(windowWidth,windowHeight)
  background(255, 0, 200);
}
skmecs
  • 36
  • 5