Render multiple layers on a high-DPI canvas

by Rajesh Danabal

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Canvas with Zoom and Drawing</title>
  <style>
    body { margin: 0; }
    canvas { border: 1px solid #000; display: block; margin: 20px auto; }
  </style>
</head>
<body>
  <canvas id="drawingCanvas" width="800" height="600"></canvas>
  <script>
    const canvas = document.getElementById("drawingCanvas");
    const ctx = canvas.getContext("2d");

    // Initial zoom level
    let zoomLevel = 1;
    let isDrawing = false;
    let lastX = 0;
    let lastY = 0;

    // Set drawing color and line width
    ctx.strokeStyle = "black";
    ctx.lineWidth = 2;

    // Handle mouse down to start drawing
    canvas.addEventListener("mousedown", (e) => {
      isDrawing = true;
      lastX = e.offsetX / zoomLevel;  // Adjust for zoom
      lastY = e.offsetY / zoomLevel;  // Adjust for zoom
    });

    // Handle mouse up to stop drawing
    canvas.addEventListener("mouseup", () => {
      isDrawing = false;
    });

    // Handle mouse move to draw on the canvas
    canvas.addEventListener("mousemove", (e) => {
      if (!isDrawing) return;
      const x = e.offsetX / zoomLevel;  // Adjust for zoom
      const y = e.offsetY / zoomLevel;  // Adjust for zoom
      
      // Scale the drawing based on zoom level
      ctx.beginPath();
      ctx.moveTo(lastX * zoomLevel, lastY * zoomLevel);  // Scale back to canvas size
      ctx.lineTo(x * zoomLevel, y * zoomLevel);  // Scale back to canvas size
      ctx.stroke();
      lastX = x;
      lastY = y;
    });

    // Zoom in or out with mouse wheel
    canvas.addEventListener("wheel", (e) => {
      e.preventDefault();
      const zoomFactor = 0.1;
      if (e.deltaY < 0) {
        zoomLevel += zoomFactor;
      } else {
        zoomLevel = Math.max(0.1, zoomLevel - zoomFactor); // Prevent zooming out too much
      }
      redrawCanvas();
    });

    // Redraw the canvas, scaling the...