Skip to main content

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

// 更新按钮创建和样式
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);