I want to add my canvas inside a specific div and I want it to be as big as the canvas size.
For example on this code I would like the canvas to be inside the div "p5-div" and to be as big as it is. Having in consideration that the size of the div is unpredictable because is set by css and this can change.
<!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>
To allocate your canvas inside an specific div you have to use this code in your setup():
function setup() {
const myCanvas = createCanvas(divWidth, divHeight);
myCanvas.parent("div-id");
}
Now, in order to know the size of the canvas it gets a bit more complicated, this is my solution:
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"))
)
}
}
Then we can do:
function setup() {
p5Div = document.getElementById("div-id");
const p5Canvas = createCanvas(Utils.elementWidth(p5Div), Utils.elementHeight(p5Div));
p5Canvas.parent(p5Div);
}