Skip to main content

HTML5 Canvas Pointer Events Tutorial

Pointer events can be useful to handle both mobile and desktop events with one handler.

To bind pointer event handlers to shapes with Konva, we can use the on() method. The on() method requires an event type and a function to be executed when the event occurs. Konva supports pointerdown, pointermove, pointerup, pointercancel, pointerover, pointerenter, pointerout, pointerleave, pointerclick, pointerdblclick events.

Note: This example works on both mobile and desktop devices.

Instructions: move your mouse/finger across the triangle to see pointer coordinates.

import Konva from 'konva';

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

const layer = new Konva.Layer();

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

const triangle = new Konva.RegularPolygon({
  x: stage.width() / 2,
  y: stage.height() / 2,
  sides: 3,
  radius: 80,
  fill: '#00D2FF',
  stroke: 'black',
  strokeWidth: 4,
});

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

triangle.on('pointermove', function () {
  const pos = stage.getPointerPosition();
  writeMessage('x: ' + pos.x + ', y: ' + pos.y);
});

triangle.on('pointerout', function () {
  writeMessage('');
});

layer.add(triangle);
layer.add(text);
stage.add(layer);