跳到主要内容

悬停时放大图像

此示例展示如何创建鼠标悬停时放大图像的效果。图像也可以拖动。

**操作说明:**将鼠标悬停在图像上以查看放大效果。

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

// Create Darth Vader image
const darthVaderImg = new Konva.Image({
  x: 110,
  y: 88,
  width: 200,
  height: 137,
  offset: {
    x: 100,
    y: 68,
  },
  draggable: true,
});
layer.add(darthVaderImg);

// Create Yoda image
const yodaImg = new Konva.Image({
  x: 290,
  y: 70,
  width: 93,
  height: 104,
  offset: {
    x: 46,
    y: 52,
  },
  draggable: true,
});
layer.add(yodaImg);

// Load Darth Vader image
const imageObj1 = new Image();
imageObj1.onload = function () {
  darthVaderImg.image(imageObj1);
};
imageObj1.src = 'https://konvajs.org/assets/darth-vader.jpg';

// Load Yoda image
const imageObj2 = new Image();
imageObj2.onload = function () {
  yodaImg.image(imageObj2);
};
imageObj2.src = 'https://konvajs.org/assets/yoda.jpg';

// Use event delegation to update pointer style and apply scaling
layer.on('mouseover', function (evt) {
  const shape = evt.target;
  document.body.style.cursor = 'pointer';
  
  // Scale up the image on hover
  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';
  
  // Scale back to normal when mouse leaves
  shape.to({
    scaleX: 1,
    scaleY: 1,
    duration: 0.2,
  });
});