How to handle mousedown and mouseup with HTML5 Canvas

To handle the mousedown and mouseup events with HTML5 Canvas, you can attach event listeners directly to the canvas element. These events are useful for creating interactive graphics, drag-and-drop functionality, or drawing applications.

Basic Syntax

canvas.addEventListener('mousedown', function(event) {
    // Handle mouse press
});

canvas.addEventListener('mouseup', function(event) {
    // Handle mouse release
});

Example: Simple Click Detection

<canvas id="myCanvas" width="400" height="300" style="border: 1px solid #000;"></canvas>

<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
let mouseDown = false;

// Draw initial state
ctx.fillStyle = '#f0f0f0';
ctx.fillRect(0, 0, 400, 300);
ctx.fillStyle = '#333';
ctx.font = '16px Arial';
ctx.fillText('Click and drag on the canvas', 50, 50);

// Handle mousedown
canvas.addEventListener('mousedown', function(event) {
    mouseDown = true;
    const rect = canvas.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    
    console.log('Mouse down at:', x, y);
    
    // Draw a red circle at click position
    ctx.fillStyle = '#ff0000';
    ctx.beginPath();
    ctx.arc(x, y, 5, 0, 2 * Math.PI);
    ctx.fill();
});

// Handle mouseup
canvas.addEventListener('mouseup', function(event) {
    if (mouseDown) {
        const rect = canvas.getBoundingClientRect();
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;
        
        console.log('Mouse up at:', x, y);
        mouseDown = false;
        
        // Draw a blue circle at release position
        ctx.fillStyle = '#0000ff';
        ctx.beginPath();
        ctx.arc(x, y, 5, 0, 2 * Math.PI);
        ctx.fill();
    }
});
</script>

Example: Drag Drawing

<canvas id="drawCanvas" width="400" height="300" style="border: 1px solid #000;"></canvas>

<script>
const drawCanvas = document.getElementById('drawCanvas');
const drawCtx = drawCanvas.getContext('2d');
let isDrawing = false;
let lastX = 0;
let lastY = 0;

// Set drawing style
drawCtx.lineWidth = 3;
drawCtx.lineCap = 'round';
drawCtx.strokeStyle = '#333';

function getMousePos(event) {
    const rect = drawCanvas.getBoundingClientRect();
    return {
        x: event.clientX - rect.left,
        y: event.clientY - rect.top
    };
}

drawCanvas.addEventListener('mousedown', function(event) {
    isDrawing = true;
    const pos = getMousePos(event);
    lastX = pos.x;
    lastY = pos.y;
});

drawCanvas.addEventListener('mousemove', function(event) {
    if (!isDrawing) return;
    
    const pos = getMousePos(event);
    drawCtx.beginPath();
    drawCtx.moveTo(lastX, lastY);
    drawCtx.lineTo(pos.x, pos.y);
    drawCtx.stroke();
    
    lastX = pos.x;
    lastY = pos.y;
});

drawCanvas.addEventListener('mouseup', function() {
    isDrawing = false;
});

// Handle mouse leaving canvas
drawCanvas.addEventListener('mouseout', function() {
    isDrawing = false;
});
</script>

Key Points

  • Coordinate Calculation: Use getBoundingClientRect() to get accurate mouse positions relative to the canvas
  • State Tracking: Use a boolean variable to track whether the mouse is currently pressed
  • Event Handling: Always handle mouseout to prevent drawing continuing when mouse leaves canvas
  • Performance: Consider throttling mousemove events for complex drawing operations

Browser Compatibility

Mouse events on canvas are supported in all modern browsers. The getBoundingClientRect() method is also widely supported.

Conclusion

Handling mousedown and mouseup events on HTML5 Canvas enables interactive graphics and drawing applications. Always calculate proper coordinates using getBoundingClientRect() for accurate positioning.

Updated on: 2026-03-15T23:18:59+05:30

902 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements