Skip to main content

Zoom Image on Hover

Instructions: Hover over an Image.

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 imageObj = new Image();
imageObj.onload = function () {
  const backgroundImage = new Konva.Image({
    x: 0,
    y: 0,
    width: width,
    height: height,
    image: imageObj,
  });
  layer.add(backgroundImage);
};

imageObj.src = 'https://new.konvajs.org/assets/space.jpg';

const zoomLevel = 2;
layer.on('mouseenter', function () {
  layer.scale({
    x: zoomLevel,
    y: zoomLevel,
  });
});

layer.on('mousemove', function (e) {
  const pos = stage.getPointerPosition();
  layer.x(-pos.x);
  layer.y(-pos.y);
});

layer.on('mouseleave', function () {
  layer.x(0);
  layer.y(0);
  layer.scale({
    x: 1,
    y: 1,
  });
});