How do I make a button created using createButton() stay on the canvas?

Hello,

I have the following code, where I want to create a p5 canvas, attach it to a div (with id of 'shootingstar'), and then create a button on that canvas.

function setup() {
    var myCanvas = createCanvas(400, 400);
    myCanvas.parent('shootingstar');

    resetButton = createButton('reset');
    resetButton.position(300, 300);
    resetButton.mousePressed(reset);
}

The problem is, the button is rendering as if the canvas.parent() command has had no effect. How do I get the button to be positioned relative to the top left corner of the canvas?

I should mention that I'm trying to keep this as simple as possible because first year students are going to be using it.

Any thoughts would be awesome! Thank you!

Answers

  • createButton() creates a DOM element - which is therefore completely separate from the canvas. button.position() just adds some inline styling to the button:

    <button value="undefined" style="position: absolute; left: 0px; top: 0px;">click me</button>

    By default position: absolute is relative to the browser window. You could set the position of the canvas in the same way and calculate button position based on canvas position; but that's rather inelegant and could lead to problems on pages with other DOM elements

    A better solution is to put the button in the same container as the canvas and do some CSS 'magic'. Here's an example modifying the example code:

    var button;
    
    function setup() {
        var myCanvas = createCanvas(100, 100);
        myCanvas.parent('sketch01');
        background(0);
        button = createButton('click me');
        // put button in same container as the canvas
        button.parent('sketch01');
        // by default this sets position relative to window...
        button.position(0, 0);
        button.mousePressed(changeBG);
    }
    
    function changeBG() {
      var val = random(255);
      background(val);
    }
    

    My html page has a target div with id of 'sketch01'. The trick is to add some CSS to this. I'd normally do this in a separate CSS file; but for our purposes you can do it inline as follows:

    <div id="sketch01" style="position: relative;"> </div>

    This ensures that any absolutely positioned child elements are positioned relative to the container wherever it is located in the window...

Sign In or Register to comment.