home ~ projects ~ socials

Make A p5.js Canvas Full Screen

Introduction

I'm working on a graphic equalizer display in p5.js to use when I'm recording blog posts for mp3s and videos. I want it to display full screen for the video. This is how I'm setting it up to do that.

HTML

<div id="p5Wrapper"></div>

Output

JavaScript

let baseWidth = 200

function findHeight(fromWidth) {
  return window.screen.height / window.screen.width * fromWidth 
}

function handleFullscreenChange() {
  if (!document.fullscreenElement) {
    resizeCanvas(baseWidth, findHeight(baseWidth))
  } else {
    resizeCanvas(displayWidth, displayHeight)
  }
}

function toggleFullscreen() {
  if (!document.fullscreenElement) {
    document.querySelector('#p5Canvas').requestFullscreen()
  } else {
    document.exitFullscreen()
  }
}

function setup() {
  const canvas = createCanvas(baseWidth, findHeight(baseWidth))
  canvas.parent('p5Wrapper')
  canvas.id('p5Canvas')
  canvas.mouseClicked(toggleFullscreen)
  document.querySelector('#p5Canvas').addEventListener(
    'fullscreenchange', handleFullscreenChange
  )
}

function draw() {
  background('skyblue')
  text('Click Me!', 20, 20)
  text(`Canvas width: ${width}`, 20, 50)
}

Details

  • This technique uses the native Fullscreen API which is listed at 97.4% Global usage on Can I Use
  • I looked at p5's built in fullscreen() function. I'd hoped it would just take care of everything, but it doesn't. You still have to deal with the escape key and resizing when the canvas when going in and out of fullscreen
  • This is wired up to use a click on the canvas to go in and out of fullscreen
  • Hitting the escape key while in fullscreen works via the 'fullscreenchange' listener
  • I'm keeping the aspect ratio the same both when the canvas is fullscreen and when it's not via the findHeight() function
  • The width for the non-fullscreen view is hard coded in the example. The width for the fullscreen view is determined automatically
  • There's some weirdness that happens to the text on the canvas in firefox on my mac if the browser is zoomed out. If you keep going in and out of fullscreen the text keeps getting smaller and smaller. I'm not sure what's going on there. Chrome doesn't have the problem which makes me think it's a bug
-- end of line --

References