Including P5js in a blog

Hello, I’m including some p5 sketches in a blogpost, but If I’m not mistaken the responsiveness will be an issue, because:

  1. we include the sketch through an iframe
  2. there is no way to make the canvas size resize nicely for different devices

I wonder if we can pass innerWidth to the canvas x dimension but yet in that case it will grow forever. We could do something like a ‘while innerWitdh is less than X value set a innerWidth and otherwise a fixed value’. But I’m just not too confident about that idea…

I’ve taken a look at how the sketches are imported in the p5js website, but they all have fixed dimensions, So I’m a bit confused about how to do it.

So far, I’ve created 2 different sketches, for phones and laptops, and a js script to set the src attribute of the iframe accordingly, but yet that’s not very flexible.

Any ideas on this?

Just in case, this is the post draft, is not yet visible for a regular visitor. In the second sketch there are 2 buttons ‘run’ and ‘stop’ to play with the sketch.

1 Like

I have the exactly same question, trying to figure it out how to embed responsive p5js iframe (I’m do not have web development background).

@cristianreynaga
Just for your interest, I found out a way, but I’m sure it’s not the best one.

You can include a fixed p5 sketch, but using media queries. In pseudocode it would be

  • less than 600px devices --> 350px sketch
    -less than 900px but more than 600px --> 600px sketch
  • more than 900px --> 900px sketch.

Another tool, could be to pass windowWidth (or a similar parameter, check in the doc) to the canvas! And that should resize.


If your sketch an files are somewhere (i.e github, gitlab etc) I can take a look.

1 Like

hi! thanks!

I went to Creative Coding Facebook Group and I could find an old post about responsiveness.

I used resizeCanvas function and I change all size/position parameters to a proportional vales related to window and height values.

Here you can see my “adaptative” sketch, it works for me, it seems responsive in mobile, but maybe it is not 100% web responsive:

Editor view: https://editor.p5js.org/cristianreynaga/sketches/2WbwK9J_j
Presentation view: https://editor.p5js.org/cristianreynaga/present/2WbwK9J_j

Excellent! I’ll use your approach too at some point.

1 Like