如何将 p5.js canvas 放置在 div 容器中?
How to position a p5.js canvas inside a div container?
到目前为止,我已经使用 document.getElementById("divName").offsetWidth
和 .offsetHeight
获得了 p5.js canvas 大小以响应其父 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>
这是我目前正在渲染的 screenshot。如您所见,蓝色方块(我的 p5.js 代码)与红色方块(div)具有相同的尺寸,但我希望它也重叠在同一位置。
非常感谢您的帮助!
参见 createCanvas
a p5.Renderer
. Set the the container as the renders parent()
的文档:
let renderer = createCanvas(sketchWidth, sketchHeight);
renderer.parent("square");
到目前为止,我已经使用 document.getElementById("divName").offsetWidth
和 .offsetHeight
获得了 p5.js canvas 大小以响应其父 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>
这是我目前正在渲染的 screenshot。如您所见,蓝色方块(我的 p5.js 代码)与红色方块(div)具有相同的尺寸,但我希望它也重叠在同一位置。
非常感谢您的帮助!
参见 createCanvas
a p5.Renderer
. Set the the container as the renders parent()
的文档:
let renderer = createCanvas(sketchWidth, sketchHeight);
renderer.parent("square");