Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put p5.js canvas in a html div

Tags:

p5.js

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.

like image 478
Meghan Rose Avatar asked Feb 26 '16 19:02

Meghan Rose


People also ask

What is the p5 js command for a new canvas?

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.

What is the purpose of the index HTML file in 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!

Can you make a website with p5 js?

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.


2 Answers

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

like image 39
fredericrous Avatar answered Sep 21 '22 10:09

fredericrous


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");
like image 100
Michael Paccione Avatar answered Sep 20 '22 10:09

Michael Paccione