createCanvas
← All Butter documentationParameters
createCanvas(width: number, height: number, mode: P2D|WEBGL = P2D)
widthThe horizontal size of your canvas.
heightThe vertical size of your canvas.
modeWhether to make a 2D mode sketch or a WebGL sketch.
Just like in a regular p5.js sketch, a Butter component starts by creating a canvas with enough room to draw your content. There are a few things to consider that are a little different from regular p5.js though!
2D vs WebGL mode
You can still use either mode in a Butter component, but for more advanced components, you'll see better performance using WebGL since the rest of Butter runs in WebGL and can share resources.
Fitting content to the canvas size
For a lot of components, you'll want users to be able to control exactly how big and what shape your canvas is, and then you can size your content to fit within that box. To do that, use windowWidth and windowHeight as the width and height of your canvas. Butter will automatically normalize the size for you so that the smallest side is 360px, meaning you only have to deal with aspect ratio changes rather than scale changes. When the user scales the component uniformly, we'll just update the pixelDensity() of your sketch to get more or less detail.
Here's an example of drawing a circle that fits into whatever size the user specifies:
function setup() {
createCanvas(windowWidth, windowHeight, WEBGL)
}
function draw() {
clear()
const d = min(width, height)
circle(0, 0, d);
}

Fitting the canvas size to content
Other times, your component will draw a visual, and the size on canvas should adapt to fit the size of that visual. The visual's size may depend on some of your fields.
To do this, create fields before calling createCanvas, and mark them as .updatesSize(). Then, you can use the .value() of your fields inside of createCanvas. Here's an example drawing text and fitting the canvas size to that text:
let txt
let font
async function setup() {
txt = createInput('Hello!').updatesSize()
font = await loadFont('').updatesSize()
textFont(font)
textSize(30)
createCanvas(
fontWidth(txt.value()),
textLeading(),
WEBGL
)
}
function draw() {
clear()
textAlign(CENTER, CENTER)
textFont(font)
textSize(30)
text(txt.value(), 0, 0)
}
