I am trying to add p5.js to the background of one section in my webpage. I am new to javascript and can't figure out how to bind the two parts together.
The createCanvas() function creates an HTML canvas on the web page, taking the desired canvas width and height as arguments. Typically, it is one of the first functions called in the setup() function. The createCanvas() function can only be called once within a p5. js sketch.
The index. html file inside the Sketch Files list contains HTML that sets up a webpage for your sketch. By default this page is empty so that it only shows the p5. js canvas, but you can add content to the page using HTML tags!
In other words, you need to create an html file that uses p5. js, which you should already have. Then you need to upload that html file, along with any resources you're using, to some kind of web host. You might also want to check out Processing.
if you are inserting multiple p5js canvas in one page and are already using the form new p5(sketch)
, you can just pass the id of your div as second parameter, like new p5(sketch, idnameofdiv)
Because the function sketch should be unique (if you don't use an IIFE), I like to put the id in the name of the sketch function as well
function sketch_idnameofdiv(p) {
p.setup = function () {
p.createCanvas(400,400);
}
p.draw = function () {
// stuff to draw
}
}
new p5(sketch_idnameofdiv, 'idnameofdiv')
if you don't need to insert multiple p5js canvas in one page, I guess you are looking for Michael Paccione's answer
You need to add code in your setup.
Make sure you have the function in a script tag in the html as well. Note you do not add # in the .parent().
var myCanvas = createCanvas(winWidth, winHeight);
myCanvas.parent("idnameofdiv");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With