Skip to main content

Shape Tooltips

HTML5 Canvas Shape Tooltips with Konva

This demo shows how to create tooltips that follow the mouse cursor when hovering over shapes. It demonstrates:

  1. Creating custom shapes using the sceneFunc
  2. Handling mouse events (mousemove, mouseout)
  3. Using multiple layers for better organization
  4. Creating dynamic tooltips that follow the cursor
import Konva from 'konva';

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

const shapesLayer = new Konva.Layer();
const tooltipLayer = new Konva.Layer();

// Create custom triangle shape
const triangle = new Konva.Shape({
  stroke: 'black',
  fill: '#00D2FF',
  strokeWidth: 1,
  sceneFunc: function (context) {
    context.beginPath();
    context.moveTo(120, 50);
    context.lineTo(250, 80);
    context.lineTo(150, 170);
    context.closePath();
    context.fillStrokeShape(this);
  },
});

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

// Create tooltip
const tooltip = new Konva.Text({
  text: '',
  fontFamily: 'Calibri',
  fontSize: 12,
  padding: 5,
  textFill: 'white',
  fill: 'black',
  alpha: 0.75,
  visible: false,
});

// Add event listeners for triangle
triangle.on('mousemove', () => {
  const mousePos = stage.getPointerPosition();
  tooltip.position({
    x: mousePos.x + 5,
    y: mousePos.y + 5,
  });
  tooltip.text('Cyan Triangle');
  tooltip.show();
});

triangle.on('mouseout', () => {
  tooltip.hide();
});

// Add event listeners for circle
circle.on('mousemove', () => {
  const mousePos = stage.getPointerPosition();
  tooltip.position({
    x: mousePos.x + 5,
    y: mousePos.y + 5,
  });
  tooltip.text('Red Circle');
  tooltip.show();
});

circle.on('mouseout', () => {
  tooltip.hide();
});

// Add shapes and tooltip to layers
shapesLayer.add(triangle);
shapesLayer.add(circle);
tooltipLayer.add(tooltip);

// Add layers to stage
stage.add(shapesLayer);
stage.add(tooltipLayer);

Instructions: Move your mouse over the shapes to see tooltips appear. The tooltips will follow your cursor and display information about each shape.