Skip to content

Positioning your canvas

Atul Varma edited this page Apr 1, 2016 · 18 revisions

By default, your p5 sketch's canvas is added to the end of the web page it's in, and no styling is applied to it.

However, it's possible to position and style it any way you want with a bit of HTML and CSS.

Let's start with a simple sketch:

<html>
  <head>
    <title>My Sketch</title>
    <script src="libraries/p5.js"></script>
    <script src="sketch.js"></script>
  </head>
  <body>
  </body>
</html>
// sketch.js

function setup() {
  createCanvas(100, 100);
  background(255, 0, 200);
}

This will display a 100x100 pink square at the top-left of your browser window.

Centering the sketch on the page

We can add a stylesheet that uses flexible box layout to vertically and horizontally center our sketch on the page:

<html>
  <head>
    <title>My Sketch</title>

    <!-- Link to our stylesheet! -->
    <link rel="stylesheet" href="style.css">

    <script src="libraries/p5.js"></script>
    <script src="sketch.js"></script>
  </head>
  <body>
  </body>
</html>
/* style.css */

html, body {
  height: 100%;
}

body {
  margin: 0;
  display: flex;

  /* This centers our sketch horizontally. */
  justify-content: center;

  /* This centers our sketch vertically. */
  align-items: center;
}

Note that at the time of this writing, flexible box layout (or "flexbox", as it's often called) is a relatively new feature in CSS. As such, the above CSS will work on the latest browsers, but older browsers may not position it accurately. To fully support older browsers, you may want to use vendor prefixing in your CSS.

Relocating the canvas

Alternatively, you may want to position your canvas in the midst of other information on your page. This can be done by using p5's p5.Element.parent() function to move our sketch inside an existing HTML element on our page, rather than leaving it at the very end of the page:

<html>
  <head>
    <title>My Sketch</title>
    <script src="libraries/p5.js"></script>
    <script src="sketch.js"></script>
  </head>
  <body>
    <p>Here is my sketch:</p>
    <div id="sketch-holder">
      <!-- Our sketch will go here! -->
    </div>
    <p>Pretty cool, eh?</p>
  </body>
</html>
// sketch.js

function setup() {
  var canvas = createCanvas(100, 100);
 
  // Move the canvas so it's inside our <div id="sketch-holder">.
  canvas.parent('sketch-holder');

  background(255, 0, 200);
}
Clone this wiki locally