Skip to main content

鼠标悬停时扩展图像

本演示展示了如何创建一个效果,当鼠标悬停在图像上时图像会扩展。这些图像也是可拖动的。

说明: 将鼠标悬停在图像上以查看它们的扩展效果。

import Konva from 'konva';

const width = window.innerWidth;
const height = window.innerHeight;

const stage = new Konva.Stage({
  container: 'container',
  width: width,
  height: height,
});

const layer = new Konva.Layer();
stage.add(layer);

// 创建达斯·维德图像
const darthVaderImg = new Konva.Image({
  x: 110,
  y: 88,
  width: 200,
  height: 137,
  offset: {
    x: 100,
    y: 68,
  },
  draggable: true,
});
layer.add(darthVaderImg);

// 创建尤达图像
const yodaImg = new Konva.Image({
  x: 290,
  y: 70,
  width: 93,
  height: 104,
  offset: {
    x: 46,
    y: 52,
  },
  draggable: true,
});
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.to({
    scaleX: 1.2,
    scaleY: 1.2,
    duration: 0.2,
  });
});

layer.on('mouseout', function (evt) {
  const shape = evt.target;
  document.body.style.cursor = 'default';
  
  // 鼠标离开时缩放回正常
  shape.to({
    scaleX: 1,
    scaleY: 1,
    duration: 0.2,
  });
});