<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Mouse Drawing App</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script>
// get the canvas element
var canvas = document.getElementById("canvas");
// set up the drawing context
var ctx = canvas.getContext("2d");
// set initial variables
var isDrawing = false;
var lastX = 0;
var lastY = 0;
// add event listeners
canvas.addEventListener("mousedown", startDrawing);
canvas.addEventListener("mousemove", draw);
canvas.addEventListener("mouseup", stopDrawing);
canvas.addEventListener("mouseout", stopDrawing);
// start drawing
function startDrawing(e) {
isDrawing = true;
lastX = e.clientX - canvas.offsetLeft;
lastY = e.clientY - canvas.offsetTop;
}
// draw
function draw(e) {
if (!isDrawing) return;
var x = e.clientX - canvas.offsetLeft;
var y = e.clientY - canvas.offsetTop;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.stroke();
lastX = x;
lastY = y;
}
// stop drawing
function stopDrawing() {
isDrawing = false;
}
</script>
</body>
</html>