How to put p5.js canvas in a html div?

by raphael_tillman , in category: Javascript , 2 months ago

How to put p5.js canvas in a html div?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 2 months ago

@raphael_tillman 

To put a p5.js canvas inside an HTML <div> element, you can create the canvas in your JavaScript code and then append it to the desired <div> element. Here's an example:

  1. First, create a HTML file and include the p5.js library in the section:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>p5.js Canvas in a Div</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
</head>
<body>
    <div id="canvasContainer"></div>
    
    <script src="sketch.js"></script>
</body>
</html>


  1. Create a JavaScript file (e.g., sketch.js) and write the code to create the p5.js canvas and append it to the
1
2
3
4
5
6
7
8
9
function setup() {
    let canvas = createCanvas(400, 400);
    canvas.parent('canvasContainer'); // Append the canvas to the div with id 'canvasContainer'
}

function draw() {
    background(220);
    ellipse(width/2, height/2, 50, 50);
}


In the above code, we create a canvas using createCanvas() and then use the parent() function to append the canvas to the <div> element with the id 'canvasContainer'.

  1. Save both files in the same directory and open the HTML file in a browser. You should see the p5.js canvas displayed inside the


This is how you can put a p5.js canvas inside an HTML <div> element.