processing / p5.js-web-editor

The p5.js Editor is a website for creating p5.js sketches, with a focus on making coding accessible and inclusive for artists, designers, educators, beginners, and anyone else! You can create, share, or remix p5.js sketches without needing to download or configure anything.
https://editor.p5js.org
GNU Lesser General Public License v2.1
1.41k stars 1.35k forks source link

Controlling canvas size in embedded iframe #1706

Open catarak opened 3 years ago

catarak commented 3 years ago

"I want to include some sketches in a blog-like article via the embed feature, so I am dealing with iframes. I am having trouble to automatically get the height of my sketch, as this is of course a cross-origin scenario, so I cannot read the canvas' height via JS.

"Is this something that could/would be solved by the API? As in: I would be able to access the sketch height via the API? Or are there even any other solutions for that, that I am missing?"

Originally posted by @trych in https://github.com/processing/p5.js-web-editor/issues/1075#issuecomment-743746148

catarak commented 3 years ago

One thing that comes to mind is that you could, in the embedded sketch, set the canvas size to windowWidth and windowHeight, and then set the width and height of the iframes to how big you want the sketches to be.

If you wanted to access the canvas from outside of the iframe, you'd have to use the web messaging api (i.e. window.postMessage and window.on("message")) and then have a handler within your sketch. This way is way more complicated and I think the first way I suggested is much simpler.