Skip to main content

HTML5 Canvas Image Events with Konva

To only detect events for non transparent pixels in an image with Konva, we can use the drawHitFromCache() method to generate a more precise image hit region. By default, events can be triggered for any pixel inside of an image, even if it's transparent. The drawHitFromCache() method also accepts an optional callback method to be executed whenever the image hit region has been created.

Note: The drawHitFromCache() method requires that the image is hosted on a web server with the same domain as the code executing it.

Instructions: Mouse over the monkey and the lion and observe the mouseover event bindings. Notice that the event is triggered for the monkey if you mouseover any portion of the image, including transparent pixels. Since we created an image hit region for the lion, transparent pixels are ignored, which enables more precise event detection.

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 text = new Konva.Text({
  x: 10,
  y: 10,
  fontFamily: 'Calibri',
  fontSize: 24,
  text: '',
  fill: 'black',
});
layer.add(text);

function writeMessage(message) {
  text.text(message);
  layer.draw();
}

const imageObj1 = new Image();
imageObj1.onload = () => {
  const monkey = new Konva.Image({
    x: 120,
    y: 50,
    image: imageObj1,
    width: 200,
    height: 200,
  });

  monkey.on('mouseover', function () {
    writeMessage('mouseover monkey (regular image)');
  });
  monkey.on('mouseout', function () {
    writeMessage('');
  });

  layer.add(monkey);
};
imageObj1.src = 'https://new.konvajs.org/assets/monkey.png';

const imageObj2 = new Image();
imageObj2.onload = () => {
  const lion = new Konva.Image({
    x: 320,
    y: 50,
    image: imageObj2,
    width: 200,
    height: 200,
  });

  // override color detection region
  lion.on('mouseover', function () {
    writeMessage('mouseover lion (with transparent pixels detection)');
  });
  lion.on('mouseout', function () {
    writeMessage('');
  });

  layer.add(lion);
  lion.cache();
  lion.drawHitFromCache();
};
imageObj2.src = 'https://new.konvajs.org/assets/lion.png';