Search code examples
javascriptkonvajs

How can I put a <button> inside a Konva stage?


I need to click on stage and change it color using a button inside it. I already managed to put a button in a div off the canvas but this time I need the button to appear inside my stage


Solution

  • You can draw a button with canvas shapes, or you can use DOM <button> with absolute position

    var stage = new Konva.Stage({
      container: 'container',
      width: window.innerWidth,
      height: window.innerHeight
    });
    
    var layer = new Konva.Layer();
    stage.add(layer);
    
    var button = new Konva.Label({
      x: 20,
      y: 20,
      opacity: 0.75
    });
    layer.add(button);
    
    button.add(new Konva.Tag({
      fill: 'black',
      lineJoin: 'round',
      shadowColor: 'black',
      shadowBlur: 10,
      shadowOffset: 10,
      shadowOpacity: 0.5
    }));
    
    button.add(new Konva.Text({
      text: 'Canvas button',
      fontFamily: 'Calibri',
      fontSize: 18,
      padding: 5,
      fill: 'white'
    }));
    
    
    button.on('click', () => {
        alert('clicked on canvas button');
    })
    
    document.querySelector('#button').addEventListener('click', () => {
        alert('clicked on DOM button');
    })
    
    layer.draw();
    #button {
      position: absolute;
      top: 30px;
      left: 160px;
    }
    <!DOCTYPE html>
    <html>
    <head>
    <meta name="description" content="Konva demo">
      <script src="https://unpkg.com/konva@^3/konva.min.js"></script>
      <meta charset="utf-8">
    </head>
    <body>
      <div id="container"></div>
      <button id="button">DOM button</button>
    </body>
    </html>