如何使用P5JS将画布扩展到父div的大小



我想将画布添加到特定的div中,并且希望它和画布大小一样大。

例如,在这段代码中,我希望画布位于div"中;p5-div";考虑到div的大小是不可预测的,因为它是由css设置的,这可能会改变。


<!doctype html>
<html lang="en">
<head>
<style>
#p5-div {
width: 50%;
height: 300px
}
</style>
</head>
<body>
<h1>My Sketch</h1>
<div id="p5-div">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js" integrity="sha512-NxocnqsXP3zm0Xb42zqVMvjQIktKEpTIbCXXyhBPxqGZHqhcOXHs4pXI/GoZ8lE+2NJONRifuBpi9DxC58L0Lw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
function setup() {
createCanvas(100, 100); // this has to be adapted in load time to the side of the div
}
function draw(){
background(33);
}
</script>
</body>
</html>

要在特定div中分配画布,必须在setup():中使用此代码

function setup() {
const myCanvas = createCanvas(divWidth, divHeight);
myCanvas.parent("div-id");
}

现在,为了知道画布的大小,它变得有点复杂,这是我的解决方案:

class Utils {
// Calculate the Width in pixels of a Dom element
static elementWidth(element) {
return (
element.clientWidth -
parseFloat(window.getComputedStyle(element, null).getPropertyValue("padding-left")) -
parseFloat(window.getComputedStyle(element, null).getPropertyValue("padding-right"))
)
}
// Calculate the Height in pixels of a Dom element
static elementHeight(element) {
return (
element.clientHeight -
parseFloat(window.getComputedStyle(element, null).getPropertyValue("padding-top")) -
parseFloat(window.getComputedStyle(element, null).getPropertyValue("padding-bottom"))
)
}
}

然后我们可以做:

function setup() {
p5Div = document.getElementById("div-id");
const p5Canvas = createCanvas(Utils.elementWidth(p5Div), Utils.elementHeight(p5Div));
p5Canvas.parent(p5Div);
}

最新更新