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>
<script src=""></script>
<meta charset="utf-8">
<title>Konva Image Events Demo</title>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #F0F0F0;
<div id="container"></div>
function writeMessage(message) {
function loadImages(sources, callback) {
var images = {};
var loadedImages = 0;
var numImages = 0;
for(var src in sources) {
for(var src in sources) {
images[src] = new Image();
images[src].onload = function() {
if(++loadedImages >= numImages) {
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() {

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

lion.on('mouseout', function() {


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