Meghan Rose
Meghan Rose

Reputation: 301

How to put p5.js canvas in a html div

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.

Upvotes: 30

Views: 38402

Answers (4)

Nikhil
Nikhil

Reputation: 3950

To be more detailed about the answer:

function setup() is a function which executes ojnly once at the startup.

function draw() is a function which executes after setup() and it reloads on every frame of the picture.

The code goes like this:

<!DOCTYPE html>
<html>
<head>
  <title>P5.js Example</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>
  <script>
    function setup() {
      var canvas = createCanvas(400, 400);
      canvas.parent('canvasForHTML');
    }

    function draw() {
      background(127);
    }
  </script>
</head>
<body>
  <h1>Canvas for visualization</h1>
  <div id="canvasForHTML"></div>
  <p>Move your mouse around to see circles.</p>
</body>
</html>

Check this: https://jsfiddle.net/sugandhnikhil/74Ltdy8z/1/

Upvotes: 4

Michael Paccione
Michael Paccione

Reputation: 2817

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");

Upvotes: 51

fredericrous
fredericrous

Reputation: 3038

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

Upvotes: 6

Kevin Workman
Kevin Workman

Reputation: 42176

P5.js gives you an html canvas that you can use for positioning your sketch.

Here is an example of using a canvas as the background of a div:

<!DOCTYPE html>
<html>
<head>
    <style>
        canvas {
           position:absolute;
           top:0;
           left:0;
           width:100%;
           height:100%;
           z-index:-1;
        }
    </style>

</head>
<body>
    <h1>Heading</h1>
    <p>paragraph 1</p>
    <p>paragraph 2</p>
    <script src="processing-1.4.1.min.js"></script>
    <div id="canvasContainer">
    <canvas data-processing-sources="rectangles.pde"></canvas>
    </div>
</body>

This is Processing.js instead of P5.js, but the idea is the same. Try googling something like "html canvas as background" for a ton of results. Try something out, and post an MCVE if you get stuck.

Upvotes: 5

Related Questions