Skip to content Skip to sidebar Skip to footer

Connecting The Html Input Page With P5.js

I want to get the data from input tags and use them in the equation. I have tried a lot a lot of solutions, nothing worked. I want it to start setup after click one button, and sta

Solution 1:

This answer uses instance mode to create a canvas with width and height set from user inputs. This allows us to call createCanvas() inside of setup. The code only allows us to create one canvas but it would not be hard to modify so that multiply canvases could be created, however, we should never call createCanvas more than once for each instance of p5.

var canvas = null;
functioncreateP5 (){
  let canvasWidth = document.getElementById("widthInput").value;
  let canvasHeight = document.getElementById("heightInput").value;
  if (canvas === null){
    canvas = newp5(function (p) {
      p.setup = function (){
        p.createCanvas(canvasWidth, canvasHeight);
      }
      p.draw = function(){
        p.background(55);
        p.stroke(0);
        p.rect(p.width/5, p.height/5, p.width/5 * 3, p.height/5 * 3);
     }
    }, "canvas-div");
  }
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.min.js"></script><divid="canvas-div"></div><inputtype="button"value="create canvas"onclick='createP5()'/><textareaid="widthInput"></textarea><textareaid="heightInput"></textarea>

Solution 2:

You're asking a few different questions:

How do I run code when a user presses a button?

There are a few ways to do this, but it sounds like you're looking for the onclick attribute. You can Google "JavaScript onclick" for a ton of resources.

How do I run a P5.js sketch from JavaScript code?

For this, you probably want to use instance mode to have more control over exactly when the sketch is created. See this page for more info.

The best advice I can give you is to start smaller. Start with a simple page that shows a single button that prints something to the console when you click it. Then add a simple P5.js sketch using instance mode. Work forward in small steps instead of trying to do everything all at once.

Good luck.

Post a Comment for "Connecting The Html Input Page With P5.js"