Skip to main content

拖放多个图片与边框高亮显示

本演示展示了如何实现图片的高亮效果。当鼠标悬停在图片上时,边框消失,当鼠标移开时,边框重新出现。

说明: 将鼠标悬停在图片上以隐藏其边框,然后在舞台上拖动它们。

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 darthVaderImg = new Konva.Image({
  x: 20,
  y: 20,
  width: 200,
  height: 137,
  stroke: 'red',
  strokeWidth: 10,
  draggable: true,
});
layer.add(darthVaderImg);

// 创建尤达图片
const yodaImg = new Konva.Image({
  x: 240,
  y: 20,
  width: 93,
  height: 104,
  draggable: true,
  stroke: 'red',
  strokeWidth: 10,
});
layer.add(yodaImg);

// 加载达斯·维德图片
const imageObj1 = new Image();
imageObj1.onload = function () {
  darthVaderImg.image(imageObj1);
};
imageObj1.src = 'https://konvajs.org/assets/darth-vader.jpg';

// 加载尤达图片
const imageObj2 = new Image();
imageObj2.onload = function () {
  yodaImg.image(imageObj2);
};
imageObj2.src = 'https://konvajs.org/assets/yoda.jpg';

// 使用事件委托更新指针样式和边框
layer.on('mouseover', function (evt) {
  const shape = evt.target;
  document.body.style.cursor = 'pointer';
  shape.strokeEnabled(false);
});

layer.on('mouseout', function (evt) {
  const shape = evt.target;
  document.body.style.cursor = 'default';
  shape.strokeEnabled(true);
});