Skip to main content

Expand Image on Hover

This demo shows how to create an effect where images expand when the mouse hovers over them. The images are also draggable.

Instructions: Hover your mouse over the images to see them expand.

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