如何将p5.js画布放置在一个div容器内部?

3

迄今为止,我已经使用 document.getElementById("divName").offsetWidth.offsetHeight 使p5.js画布的大小与其父div容器的大小相对应,但是我还没有弄清楚为什么它的位置不能自适应。下面是我的应用程序的简化版本。

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>

以下是我正在渲染的内容截图。如您所见,蓝色正方形(我的 p5.js 代码)与红色正方形(div)具有相同的尺寸,但我希望它也可以在相同位置重叠。

1个回答

1
查看 createCanvasp5.Renderer 的文档。将容器设置为渲染器的parent()
let renderer = createCanvas(sketchWidth, sketchHeight);
renderer.parent("square");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接