4

I have been trying to set a p5.js canvas inside a div, and use the divs width to control the canvas width, within a jekyll post. In the markdown file I am constructing a div that I know sits at the top of the post.

<div id="myCanvas"</div>
<script src="/js/p5Sketches/firstP5Sketch.js" type="text/javascript"></script>

In the javascript I have the p5.js canvas assigned to the div. I have tried to get the parent's div clientWidth but I am getting some really strange outputs.

var canvasDiv = document.getElementById('myCanvas');
var width = canvasDiv.clientWidth;

function setup() {
  var sketchCanvas = createCanvas(width,450);
  sketchCanvas.parent("myCanvas");
}

function draw() {
  if (mouseIsPressed){
    fill(0);
  } else {
    fill(255);
  }
  ellipse(mouseX, mouseY, 40, 40);

  if (keyIsPressed == true){
    clear();
  }
}

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

When I print out the canvasDiv attributes I get the correct clientWidth value (844px), but then print out the width variable and it is 1244px. In the chrome inspector the p5 canvas ends up being width=100px.

<canvas id="" width="200" height="900" style="width: 100px !important; height: 450px !important;" class=""></canvas>

The value is not passed on to the p5 canvas, and I can't work out why. As an aside I am not using any css to style the myCanvas or canvas elements.

Thanks in advance.

2
  • All I can see is a tiny mistake like this: <div id="myCanvas"</div> Tag isn't closed?
    – Adib
    Commented May 7, 2016 at 0:48
  • Thanks Adib, I did have the closing > in the code, it was a typo in the post.
    – C.Bam
    Commented May 7, 2016 at 2:44

1 Answer 1

8

You need to capture the parent elements information within setup()

The default width and height for setup() is 100x100. And if width isn't defined inside setup(), it'll be overwritten with the default value. From the documentation:

The system variables width and height are set by the parameters passed to this function. If createCanvas() is not used, the window will be given a default size of 100x100 pixels.

https://p5js.org/reference/#/p5/createCanvas

Which I tested and proved in this image:

width and height are pre-defined by setup() already

The following is the correct code you should replace your setup() function with:

function setup() {
    var canvasDiv = document.getElementById('myCanvas');
    var width = canvasDiv.offsetWidth;
    var sketchCanvas = createCanvas(width,450);
    console.log(sketchCanvas);
    sketchCanvas.parent("myCanvas");
}
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.