1

I am trying to embed the p5.js output canvas into my webpage by following this tutorial. I hope the canvas will display where I placed it inside the HTML body. However, it will always be at the very bottom of my page. I tried to play around with CSS, especially position and display, but nothing special other than display: none;... The same thing happened when I tried to place the script inside the body. Moreover, the canvases will overlap if multiple scripts are included.

Here are some example codes:

index.html

<!doctype html>
<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/p5@1.5.0/lib/p5.min.js"></script>
    <script src="test.js"></script>
  </head>
  <body>
    <h1>Hello World</h1>
    <p>This is a sentence</p>
</body>
</html>

test.js

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  circle(200,200,50,50);
}
Will
  • 113
  • 1
  • 8
  • Please share a description or sketch of your expected result and your attempts at adding CSS or a parent container to the canvas. Odds are, [How to get p5.js to create canvas at certain position](https://stackoverflow.com/questions/63403700/how-to-get-p5-js-to-create-canvas-at-certain-position) or [How to position a p5.js canvas inside a div container?](https://stackoverflow.com/questions/60743491/how-to-position-a-p5-js-canvas-inside-a-div-container) solve the problem by adding the canvas to a parent container, then styling the canvas and parent however you want using normal CSS. – ggorlen Oct 26 '22 at 15:23

1 Answers1

1

In order to reposition the canvas, you should use CSS. The best way to do this is to add the canvas to a parent HTML element and apply the CSS to that.

I found a good way to do this here:

First, when declaring the canvas, store it as a variable

function setup() {
    var canvas = createCanvas(400, 400);
    canvas.parent('canvas'); //'canvas' is the id of the target HTML element
}

Then add the div below and set the class to canvas-body

<div class="canvas-body" id="canvas"></div>

And in your CSS file, define canvas-body

.canvas-body {
  text-align:center;
  /* text-align works, but there might be a more proper way to align to the center */
}
Henhen1227
  • 392
  • 1
  • 3
  • 12