Nico-Mayer / p5-vue

Simply add p5 to your Vue and Nuxt projects ✌️
https://p5vue-homepage.vercel.app/
12 stars 0 forks source link

How to make the canvas responsive? resizable #2

Closed dataexcess closed 11 months ago

dataexcess commented 1 year ago

Hello,

Can you show me a way to dictate the canvas size from the outside? Now I have to set the canvas size in the p5 code and I don't know how I can circumvent it so that it simply takes the size of the parent element (from vue)...

Thanks!

WangShuan commented 1 year ago

Hi, I think maybe you can set parent element's id to my-section, and then in the setup() use this to set canvas size:

p5.setup = () => {
  const section = document.getElementById('my-section');
  p5.createCanvas(section.offsetWidth, section.offsetHeight);
}
dataexcess commented 1 year ago

Although that's a good idea it won't respond when resizing the window right?

WangShuan commented 1 year ago

@dataexcess Hi, I had try resized and it work for me, you can try too!

my code:

const sketch = (p5) => {
  p5.setup = () => {
    const section = document.getElementById('background-section');
    p5.createCanvas(section.offsetWidth, section.offsetHeight);
  }

  p5.draw = () => {
    for (let x = 0; x < p5.width; x += 50) {
      for (let y = 0; y < p5.height; y += 50) {
        p5.rect(x, y, p5.mouseX / 5);
      }
    }
  }

  p5.windowResized = () => {
    const section = document.getElementById('background-section');
    p5.resizeCanvas(section.offsetWidth, section.offsetHeight);
  }
}