Practical p5.js Canvas Management: Creation, Parent Binding, Dynamic Resizing, Scrollbar Removal, and Deletion

If a p5.js sketch includes core lifecycle functions like setup() or draw() with out explicit canvas initialization, p5.js automatically appends a 100x100 pixel <canvas> to the <body> element.

function setup() {
  background(200);
}

To define custom dimensions, use createCanvas(width, height) and pass numeric values for width and height. An optional third parameter, WEBGL, enables 3D rendering contexts.

function setup() {
  createCanvas(400, 250);
  background(180);
}

Bind Canvas to a Specific Cotnainer

By default, createCanvas() adds the canvas to the end of <body>. To place it inside a pre-existing DOM element:

  1. Retrieve the target container (using p5.js’s select() for cleaner integration)
  2. Store the canvas reference returned by createCanvas()
  3. Call .parent(container) on the canvas object
<span>top placeholder</span>
<div id="target-box"></div>
<span>bottom placeholder</span>

<script>
function setup() {
  const targetDiv = select('#target-box');
  const sketchCanvas = createCanvas(400, 250);
  sketchCanvas.parent(targetDiv);
  background(150);
}
</script>

Full-Page Scrollbar-Free Canvas

Use p5.js’s built-in windowWidth and windowHeight constants to match viewport dimensions, but two fixes are required to eliminate unwanted margins and scrollbars:

  1. Remove default margin and padding from <html> and <body>
  2. Set the canvas’s CSS display property to block
<style>
  html, body {
    margin: 0;
    padding: 0;
    overflow: hidden;
  }
</style>

<script>
let sketchCanvas;

function setup() {
  sketchCanvas = createCanvas(windowWidth, windowHeight);
  sketchCanvas.style('display', 'block');
  background(120);
}
</script>

Dynamically Resize Canvas on Viewport Change

Use the windowResized() lifecycle hook to detect viewport adjustments, then update canvas dimensions with resizeCanvas(width, height). Re-render a bcakground to clear leftover content after resizing.

<style>
  html, body {
    margin: 0;
    padding: 0;
    overflow: hidden;
  }
</style>

<script>
let sketchCanvas;

function setup() {
  sketchCanvas = createCanvas(windowWidth, windowHeight);
  sketchCanvas.style('display', 'block');
  background(120);
}

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
  background(120);
}
</script>

For additional layout control, position(x, y) can set the canvas’s absolute page coordinates.

Delete the Canvas

To remove the canvas entirely (e.g., when replacing a sketch with media elements), call noCanvas() at any point in the sketch:

noCanvas();

Tags: p5.js Canvas web development creative coding frontend

Posted on Fri, 31 Jul 2026 16:50:42 +0000 by nealios