1

I'm trying to make the canvas with p5.js resize together with a div in which it is in when clicking on a button that extends this div giving it additional height. I don't need the canvas to reload, instead I just need it to add some additional height. Is there a way to do it? I tried making the canvas width 100% and height: auto, but it doesn't work. Please, see the code below:

<div class="canvas-wrapper">
    <div id="canvas"></div>
</div>

<button type="button" class="button" id="extend-canvas">Extend</button>

Scripts:

function setup() {
    var myCanvas = createCanvas(498, 598);
    myCanvas.parent('canvas');
 }

$( "#extend-canvas" ).click(function() {
    var canvasHeight = $(".canvas-wrapper").height();
    $(".canvas-wrapper").height(canvasHeight + 300);
});

CSS:

.canvas-wrapper {
    margin: 0 auto;
    background: #fff;
    width: 500px;
    height: 600px;
    position: relative;
}

#canvas canvas {
    width: 100% !important;
    height: auto !important;
}
mugx
  • 9,869
  • 3
  • 43
  • 55
Kaori
  • 49
  • 1
  • 7
  • https://github.com/processing/p5.js/issues/207 Resize using c.size(width-10, height-10); (You have to load the p5.dom.js add-on to use the size method.) – GhitaB Dec 30 '17 at 18:29
  • This works, but the canvas reloads and becomes blank and all the information I add to it (I drew some lines with my mouse) disappears. – Kaori Dec 30 '17 at 19:03
  • https://p5js.org/reference/#/p5/resizeCanvas – GhitaB Dec 30 '17 at 20:46

1 Answers1

7

You can use the resizeCanvas() function for this. More info can be found in the reference.

Here's an example that resizes the canvas to match the screen width and height:

function setup() {
  createCanvas(windowWidth, windowHeight);
}

function draw() {
  background(0, 100, 200);
}

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
}

But you could also get the width and height of the div and set the canvas size to that.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
  • 1
    @Kaori One way around that is to first draw everything to a buffer (the `createGraphics()` function is your friend), resize the canvas, then draw the buffer back to the canvas. – Kevin Workman Dec 30 '17 at 19:02
  • This works, but the canvas reloads and becomes blank and all the information I add to it (I drew some lines with my mouse) disappears. – Kaori Dec 30 '17 at 19:03