HTML5 Canvas 隐藏和显示图形教程
要使用 Konva 隐藏和显示形状,我们可以在实例化形状时设置 visible 属性,或者使用 hide()
和 show()
方法。
说明: 点击按钮显示和隐藏形状。
- 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); // 更新按钮创建和样式 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 = '显示'; showBtn.onclick = () => rect.show(); buttonContainer.appendChild(showBtn); const hideBtn = document.createElement('button'); hideBtn.textContent = '隐藏'; 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)}>显示</button> <button onClick={() => setVisible(false)}>隐藏</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">显示</button> <button @click="hideShape">隐藏</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>