HTML5 Canvas Image Events with Konva

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.

Konva Image_Events Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Image Events Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
function writeMessage(message) {
text.text(message);
}
function loadImages(sources, callback) {
var images = {};
var loadedImages = 0;
var numImages = 0;
for (var src in sources) {
numImages++;
}
for (var src in sources) {
images[src] = new Image();
images[src].onload = function () {
if (++loadedImages >= numImages) {
callback(images);
}
};
images[src].src = sources[src];
}
}
function buildStage(images) {
var monkey = new Konva.Image({
image: images.monkey,
x: 120,
y: 50,
});

var lion = new Konva.Image({
image: images.lion,
x: 280,
y: 30,
});

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

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

lion.on('mouseover', function () {
writeMessage('mouseover lion');
});

lion.on('mouseout', function () {
writeMessage('');
});

lion.cache();
lion.drawHitFromCache();

layer.add(monkey);
layer.add(lion);
layer.add(text);
stage.add(layer);
}
var stage = new Konva.Stage({
container: 'container',
width: 578,
height: 200,
});

var layer = new Konva.Layer();

var text = new Konva.Text({
x: 10,
y: 10,
fontFamily: 'Calibri',
fontSize: 24,
text: '',
fill: 'black',
});

var sources = {
lion: '/assets/lion.png',
monkey: '/assets/monkey.png',
};

loadImages(sources, buildStage);
</script>
</body>
</html>
Enjoying Konva? Please consider to support the project.