Skip to main content

HTML5 Canvas Hide and Show Shape Tutorial

To hide and show a shape with Konva, we can set the visible property when we instantiate a shape, or we can use the hide() and show() methods.

Instructions: Click on the buttons to show and hide the shape.

import Konva from 'konva';

const stage = new Konva.Stage({
  container: 'container',
  width: window.innerWidth,
  height: window.innerHeight,
});

const layer = new Konva.Layer();
stage.add(layer);

const rect = new Konva.Rect({
  x: stage.width() / 2 - 50,
  y: stage.height() / 2 - 25,
  width: 100,
  height: 50,
  fill: 'green',
  stroke: 'black',
  strokeWidth: 4,
});
layer.add(rect);

// update button creation and styling

const buttonContainer = document.createElement('div');
buttonContainer.style.position = 'absolute';
buttonContainer.style.zIndex = 1;
buttonContainer.style.padding = '10px';
buttonContainer.style.top = '0px';
buttonContainer.style.left = '0px';

const showBtn = document.createElement('button');
showBtn.textContent = 'Show';
showBtn.onclick = () => rect.show();
buttonContainer.appendChild(showBtn);

const hideBtn = document.createElement('button');
hideBtn.textContent = 'Hide';
hideBtn.onclick = () => rect.hide();
buttonContainer.appendChild(hideBtn);

document.body.appendChild(buttonContainer);

layer.draw();