Luca Milanesio
Luca Milanesio

Reputation: 91

Is there a way to resize a p5js canvas in a bootstrap Div element?

I am trying to create a p5js canvas in a bootstrap grid. Each div element of the grid should have their own p5js canvas. I also want this canvases to resize when the browser is scaled.

This is my bootstrap div grid, which contains the div element i want the canvas to be in

<div class="container">
  <div class="row">
    <div class="col-sm-4" id="col_1">
      <script src="my_script.js"></script>
    </div>
    <div class="col-sm-4" style="background-color: #00FFFF;">
      <h3>Column 2</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
      <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
    </div>
    <div class="col-sm-4" style="background-color:  #ffff00;">
      <h3>Column 3</h3>        
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
      <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
    </div>
  </div>
</div>

and here is my script where i create the canvas parented to the div element

var canvasDiv = document.getElementById('col_1');
var width = canvasDiv.offsetWidth;
var height = canvasDiv.offsetHeight;
function setup() {
let render = createCanvas(width, height);
render.parent('col_1');
}

function draw() {
background(0, 100, 200);
fill(255, 0, 0);
ellipse(width/2, height/2, 40, 40);
}

function windowResized() {
resizeCanvas(width, height);
}

When i run my script in the browser you can see in this image that while the canvas seems to be properly scaled it does not have the same dimensions of the second and the third elements in the grid.

Furthermore when i try to resize the browser the canvas does not resize, while it position seems to change according to the bootstrap grid, as you can see here.

Upvotes: 0

Views: 780

Answers (1)

Luca Milanesio
Luca Milanesio

Reputation: 91

Thank you @statox for your comment, it helped me figuring out what was wrong. I have made some changes to the script and everything seems to be ok. I needed to gave a fixed height to the canvas and made a small adjustment to the margin, in order to keep everything in shape. Of course there is room for improvement, but for the moment i'm happy with the result. This is the code:

var canvasDiv = document.getElementById('col_1');

function setup() {
var width = canvasDiv.offsetWidth;
var height = canvasDiv.offsetHeight;
let render = createCanvas(width, 200);
render.parent("col_1");
render.style('margin-left', '-15px');
}

function draw() {
background(0, 100, 200);
fill(255, 0, 0);
ellipse(width/2, height/2, 40, 40);
}

function windowResized() {
var width = canvasDiv.offsetWidth;
var height = canvasDiv.offsetHeight;
resizeCanvas(width, 200);
}

and here a couple of images where you can see the result on a normal window and a scaled window.

Upvotes: 1

Related Questions