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:
- Retrieve the target container (using p5.js’s
select()for cleaner integration) - Store the canvas reference returned by
createCanvas() - 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:
- Remove default
marginandpaddingfrom<html>and<body> - Set the canvas’s CSS
displayproperty toblock
<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();