OWolf

2024-09-09 web, development, javascript

How to Handle HTML5 Canvas Mouse and Touch Interactions

By O. Wolfson

To add interactivity to the HTML canvas, we add event listeners for mouse and touch events.

For mouse interactions we add click, mousedown, mouseup, and mousemove listeners. For touch events we use touchstart, touchend touchcancel, touchmove, and touchdown listeners.

The code below sets up the event listeners for mouse interactions. On mousedown the boolean variable ‘mousedown’ is set true. This condition allows the coordinates of the mouse to be tracked and the drawSpheres() function to be fired. The drawShperes() function uses HTML5 canvas methods to draw arc circles onto the canvas surface.

JavaScript
let mousedown = false;

canvas.addEventListener("mousedown", function (event) {
  mousedown = true;
});

canvas.addEventListener("mouseup", function (event) {
  mousedown = false;
});

canvas.addEventListener("mousemove", function (event) {
  if (mousedown) {
    let data = {
      x: event.offsetX,
      y: event.offsetY,
      radius: 4,
    };
    drawSpheres(data);
  }
});

canvas.addEventListener("click", function (event) {
  let data = {
    x: event.offsetX,
    y: event.offsetY,
    radius: 4,
  };
  drawSpheres(data);
});

The code below sets up the event listeners for touch interactions.

JavaScript
function startup() {
  const el = document.getElementById("canvas");
  el.addEventListener("touchstart", handleStart);
  el.addEventListener("touchend", handleEnd);
  el.addEventListener("touchcancel", handleCancel);
  el.addEventListener("touchmove", handleMove);
  el.addEventListener("touchdown", handleTouchdown);
}
document.addEventListener("DOMContentLoaded", startup);

const handleStart = () => {
  mousedown = true;
};

const handleEnd = () => {
  mousedown = false
};

const handleCancel = () => {}

const handleMove = (event) => {
  if (mousedown) {
    //use preventDefault to disable scroll.
    event.preventDefault();
    let data = {
      x: event.touches[0].clientX,
      y: event.touches[0].clientY,
      radius: 10,
    };
    drawSpheres(data);
  }
};

Find the HTML and JavaScript code for this interactive canvas here. View source on the document to see the code.