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.
- Vanilla
- React
- Vue
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);
import React, { useState } from 'react';
import { Stage, Layer, Rect } from 'react-konva';
function App() {
const [visible, setVisible] = useState(true);
return (
<div style={{ position: 'relative' }}>
<div style={{ position: 'absolute', zIndex: 1, padding: '10px' }}>
<button onClick={() => setVisible(true)}>Show</button>
<button onClick={() => setVisible(false)}>Hide</button>
</div>
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
<Rect
x={window.innerWidth / 2 - 50}
y={window.innerHeight / 2 - 25}
width={100}
height={50}
fill="green"
stroke="black"
strokeWidth={4}
visible={visible}
/>
</Layer>
</Stage>
</div>
);
}
export default App;
<template>
<div style="position: relative;">
<div style="position: absolute; z-index: 1; padding: 10px;">
<button @click="showShape">Show</button>
<button @click="hideShape">Hide</button>
</div>
<v-stage :config="stageSize">
<v-layer>
<v-rect :config="rectConfig"/>
</v-layer>
</v-stage>
</div>
</template>
<script setup>
import { ref } from 'vue';
const stageSize = {
width: window.innerWidth,
height: window.innerHeight
};
const visible = ref(true);
const rectConfig = {
x: window.innerWidth / 2 - 50,
y: window.innerHeight / 2 - 25,
width: 100,
height: 50,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
visible: visible.value
};
const showShape = () => {
visible.value = true;
rectConfig.visible = true;
};
const hideShape = () => {
visible.value = false;
rectConfig.visible = false;
};
</script>