Search code examples
javascripthtmlcssflexboxp5.js

How to position a p5.js canvas inside a div container?


So far I’ve got the p5.js canvas size to react to its parent div container size using document.getElementById("divName").offsetWidth and .offsetHeight but I haven’t managed to work out why it is not sharing its position as well. Here’s a simplified version of my app.

p5.js:

var sketchWidth;
var sketchHeight;

function setup() {
  sketchWidth = document.getElementById("square").offsetWidth;
  sketchHeight = document.getElementById("square").offsetHeight;
  createCanvas(sketchWidth, sketchHeight);
}

function draw() {
  background(0,0,255);
}

function windowResized() {
  sketchWidth = document.getElementById("square").offsetWidth;
  sketchHeight = document.getElementById("square").offsetHeight;
  resizeCanvas(sketchWidth, sketchHeight);
}

HTML:

<html>
  <body>
    <div id="squareContainer">
      <div id="square">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>
        <script src="square.js"></script>
      </div>
    </div>
  </body>

  <style>
    body {
      background-color: black;
    }

    #squareContainer {
      display: flex;
      width: 50%;
      height: 50%;
      margin: 0 auto;
      background-color: white;
    }

    #square {
      box-sizing: border-box;
      width: 80%;
      height: 80%;
      margin: auto;
      background-color: red;
    }
  </style>
</html>

And here is a screenshot of what I’m currently rendering. As you can see, the blue square (my p5.js code) has the same dimensions as the red square (the div) but I would like it to also be overlapping at the same position.


Solution

  • See the documentation of createCanvas a p5.Renderer. Set the the container as the renders parent():

    let renderer = createCanvas(sketchWidth, sketchHeight);
    renderer.parent("square");