Skip to main content

Planets Image Map

Instructions: Mouse over the planets to see their names and use the check box to show and hide the map overlay.

import Konva from 'konva';

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

const planetsLayer = new Konva.Layer();
const circlesLayer = new Konva.Layer();
const messageLayer = new Konva.Layer();

stage.add(planetsLayer);
stage.add(circlesLayer);
stage.add(messageLayer);

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

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

const planets = {
Mercury: {
x: 46,
y: 126,
radius: 32,
},
Venus: {
x: 179,
y: 126,
radius: 79,
},
Earth: {
x: 366,
y: 127,
radius: 85,
},
Mars: {
x: 515,
y: 127,
radius: 45,
},
};

// create checkbox

const container = document.createElement('div');
container.style.position = 'absolute';
container.style.top = '10px';
container.style.left = '10px';
container.style.zIndex = '99999';
container.innerHTML = `  <label style="color: white;">
    <input type="checkbox" id="checkbox" />
    Show map overlay
  </label>`;
document.body.appendChild(container);

// draw shape overlays

for (const key in planets) {
const planet = planets[key];
const planetOverlay = new Konva.Circle({
x: planet.x,
y: planet.y,
radius: planet.radius,
});

planetOverlay.on('mouseover', () => {
writeMessage(key);
});
planetOverlay.on('mouseout', () => {
writeMessage('');
});

circlesLayer.add(planetOverlay);
}

const checkbox = document.getElementById('checkbox');
checkbox.addEventListener('click', () => {
const shapes = circlesLayer.getChildren();
shapes.forEach(shape => {
const f = shape.fill();
shape.fill(f === 'red' ? null : 'red');
});
});

// load the image

Konva.Image.fromURL('https://konvajs.org/assets/planets.png', (planetsImage) => {
planetsLayer.add(planetsImage);
});