Blog>
Snippets

Using Touch Events with Canvas

Capture touch events on a canvas element to create interactive drawings and gestures recognition in a web application.
// Get the canvas element and its context
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// Set up touch event listeners
function setupTouchEvents() {
    canvas.addEventListener('touchstart', handleTouchStart, false);
    canvas.addEventListener('touchmove', handleTouchMove, false);
}

// Handle touch start
function handleTouchStart(e) {
    e.preventDefault();
    const touch = e.touches[0];
    const mouseEvent = createMouseEvent('mousedown', touch);
    canvas.dispatchEvent(mouseEvent);
}

// Handle touch move
function handleTouchMove(e) {
    e.preventDefault();
    const touch = e.touches[0];
    const mouseEvent = createMouseEvent('mousemove', touch);
    canvas.dispatchEvent(mouseEvent);
}

// Utility function to convert touch event to mouse event
function createMouseEvent(type, touch) {
    return new MouseEvent(type, {
        clientX: touch.clientX,
        clientY: touch.clientY
    });
}

// Start listening for touch events
setupTouchEvents();
This code snippet sets up touch events on a canvas element to simulate mouse events for touch interactions. It listens for touchstart and touchmove events, prevents their default actions to avoid scrolling, and dispatches corresponding mousedown and mousemove events to the canvas. The createMouseEvent utility function is used to convert touch events into mouse events. This allows the canvas to handle touch-based drawing as if it were being done with a mouse.