HTML5 Canvas Desktop and Mobile Events Support Tutorial

Note: this demo may be outdate, because modern browsers support pointer events. And you can use pointer events in Konva too. See Pointer Events Demo. But if you prefer not to use pointer events, keep reading…

To add event handlers to shapes that work for both desktop and mobile applications with Konva, we can use the on() method and pass in paired events.
For example, in order for the mousedown event to be triggered on desktop and mobile applications, we can use the "mousedown touchstart" event pair to cover both mediums.
In order for the mouseup event to be triggered on both desktop and mobile applications, we can use the "mouseup touchend" event pair.
We can also use the "dblclick dbltap" event pair to bind a double click event that works for both desktop and mobile devices.

Instructions: Mousedown, mouseup, touchstart, or touchend the circle on either a desktop or mobile device to observe the same functionality.

Konva Desktop_and_Mobile Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Desktop and Mobile Events Support 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);
}

var stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
});

var layer = new Konva.Layer();

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

var circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2 + 10,
radius: 70,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
});

/*
* mousedown and touchstart are desktop and
* mobile equivalents so they are often times
* used together
*/
circle.on('mousedown touchstart', function () {
writeMessage('Mousedown or touchstart');
});
/*
* mouseup and touchend are desktop and
* mobile equivalents so they are often times
* used together
*/
circle.on('mouseup touchend', function () {
writeMessage('Mouseup or touchend');
});

layer.add(circle);
layer.add(text);

// add the layer to the stage
stage.add(layer);
</script>
</body>
</html>
Enjoying Konva? Please consider to support the project.