Execute p5.js within single webpage

Hi,
I tried to execute p5.js code using a single webpage but does not work. why?
below is the code:

<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <style> 
    body { 
    padding: 30px;
    text-align:center;
  margin: 0; } 
  
  canvas {
    outline: black 3px solid;
  border-radius: 12px;
}
    </style>
  <!--<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.js"></script>-->
    <script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.js"></script>
</head>

<body>
  <script>
  function setup() {
createCanvas(480, 120);
}


function draw() {
if (mouseIsPressed) {
fill(0);
} else {
fill(255);
}
ellipse(mouseX, mouseY, 80, 80);
}
  </script>
</body>
</html>

I tried
<body onload="script()">, <body onload="setup()"> can call to function using button but did not work. Can anybody help?

thank you

What does mean “Did not work”?

For me its working fine:

hi
thanks good to see that it should work on same page.

But the problem for me remains. In blogger blog it does not work somehow. I added <script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.js"></script> in the same blog page, in the main html template and also tried in the layout. The page shows nothing, no canvas.

Your problem is that the script loads and runs before the browser has loaded the page.
So you need to defer the loading of the script by

<script defer src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.js"></script>

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.