Quiero agregar mi lienzo dentro de un div específico y quiero que sea tan grande como el tamaño del lienzo.
Por ejemplo, en este código me gustaría que el lienzo esté dentro del div "p5-div" y que sea tan grande como es. Teniendo en cuenta que el tamaño del div es impredecible porque lo establece css y esto puede cambiar.
<!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>Para asignar su lienzo dentro de un div específico, debe usar este código en su setup() :
function setup() { const myCanvas = createCanvas(divWidth, divHeight); myCanvas.parent("div-id"); }Ahora, para saber el tamaño del lienzo se vuelve un poco más complicado, esta es mi solución:
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")) ) } }Entonces podemos hacer:
function setup() { p5Div = document.getElementById("div-id"); const p5Canvas = createCanvas(Utils.elementWidth(p5Div), Utils.elementHeight(p5Div)); p5Canvas.parent(p5Div); }