简体   繁体   中英

How to set canvas width / height using parent divs attributes

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.

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:

宽度和高度已经由setup()预定义

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM