跳到主要内容

HTML5 Canvas 隐藏和显示图形教程

要使用 Konva 隐藏和显示图形,可以在实例化图形时设置 visible 属性,也可以使用 hide()show() 方法。

**操作说明:**单击按钮以显示或隐藏图形。

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);