如何在div容器中定位p5.js画布



到目前为止,我已经让p5.js画布大小使用document.getElementById("divName").offsetWidth.offsetHeight对其父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(具有相同的尺寸,但我希望它也在相同的位置重叠。

请参阅createCanvasp5.Renderer的文档。将容器设置为渲染parent():

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

最新更新