Is there a way to use an external canvas as the canvas p5 uses

Is there a way to use the <canvas> tag as the p5 canvas?

Background

Non really, I just want to create a premade canvas in my HTML

What I’ve tried

I try looking at the doc and searching on google, I could not find anything.

you can! simply get a reference with select() and throw it into image, for example:

https://editor.p5js.org/micuat/sketches/b5ioarAI4

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = canvas.height = 200;
ctx.fillStyle = 'steelblue';
ctx.fillRect(0, 0, 200, 200);
ctx.fillStyle = 'plum';
ctx.fillRect(10, 10, 150, 100);


let canvasRef;
function setup() {
  createCanvas(400, 400);
  canvasRef = select('#canvas')
}

function draw() {
  background(220);
  image(canvasRef, mouseX, mouseY)
}

of course if you know how to work with canvas API, you can call those functions through drawingContext reference instead of image().

Edit:

I noticed what you meant is just to use <canvas> as a place where p5.js draws… in that case, this guide helps:

2 Likes

So I just use global mode?

sorry for the confusion, you can do it both with global and instance mode! just you need to use parent to fit the canvas to wherever you want
https://editor.p5js.org/micuat/sketches/Gj7qYiSSr

function setup() {
  createCanvas(400, 400).parent("#p5sketch");
}

function draw() {
  background(220);
}

nonetheless this takes <div> as a destination of the canvas to place, not selecting <canvas> itself. I don’t know if it’s possible to “attach” p5 sketch to a given <canvas> (unless copying the content of p5.js into a given canvas, just like the other way round of my “wrong” example above)

oof okay :frowning:

its fine thanks anyway, ill just work around it

1 Like