简体   繁体   English

如何在 div 容器内放置 p5.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.到目前为止,我已经使用document.getElementById("divName").offsetWidth.offsetHeight获得了 p5.js 画布大小以对其父 div 容器大小做出反应,但我还没有弄清楚为什么它不共享其位置以及。 Here's a simplified version of my app.这是我的应用程序的简化版本。

p5.js: p5.j​​s:

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:

<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.如您所见,蓝色方块(我的 p5.js 代码)与红色方块(div)具有相同的尺寸,但我希望它也重叠在同一位置。

Thanks very much for any help!非常感谢您的帮助!

See the documentation of createCanvas a p5.Renderer .请参阅createCanvas a p5.Renderer的文档。 Set the the container as the renders parent() :将容器设置为渲染parent()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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