Web-based Drawing Pad JavaScript, Canvas

👤 Sharing: AI
```javascript
<!DOCTYPE html>
<html>
<head>
<title>Simple Drawing Pad</title>
<style>
body {
  font-family: sans-serif;
  text-align: center;
}

canvas {
  border: 1px solid #000;
  cursor: crosshair;
}

#controls {
  margin-top: 10px;
}
</style>
</head>
<body>

<h1>Simple Drawing Pad</h1>

<canvas id="drawingCanvas" width="600" height="400"></canvas>

<div id="controls">
  <label for="colorPicker">Color:</label>
  <input type="color" id="colorPicker" value="#000000">

  <label for="lineWidth">Line Width:</label>
  <input type="number" id="lineWidth" value="5" min="1" max="20">

  <button id="clearButton">Clear</button>
</div>

<script>
  const canvas = document.getElementById('drawingCanvas');
  const ctx = canvas.getContext('2d');

  let painting = false;

  function startPosition(e) {
    painting = true;
    draw(e); // Draw a dot on click
  }

  function finishedPosition() {
    painting = false;
    ctx.beginPath(); // Reset path
  }

  function draw(e) {
    if (!painting) return;

    const color = document.getElementById('colorPicker').value;
    const lineWidth = document.getElementById('lineWidth').value;

    ctx.lineWidth = lineWidth;
    ctx.lineCap = 'round';
    ctx.strokeStyle = color;

    ctx.lineTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
  }

  canvas.addEventListener('mousedown', startPosition);
  canvas.addEventListener('mouseup', finishedPosition);
  canvas.addEventListener('mouseout', finishedPosition);
  canvas.addEventListener('mousemove', draw);

  // Clear Canvas Button
  const clearButton = document.getElementById('clearButton');
  clearButton.addEventListener('click', () => {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
  });
</script>

</body>
</html>
```
👁️ Viewed: 9

Comments