<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#myCanvas {
border: 1px solid #ccc
}
</style>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById("myCanvas");
let context = canvas.getContext("2d");
context.lineWidth = 5;
context.strokeStyle = "red";
context.fillStyle = "#fff";
let flag = false;
//鼠标按下
canvas.onmousedown = function(e) {
flag = true;
context.beginPath()
context.moveTo(e.clientX, e.clientY);
}
//鼠标抬起
canvas.onmouseup = function(e) {
flag = false;
}
//鼠标滑动
canvas.onmousemove = function(e) {
if (flag) {
context.lineTo(e.clientX, e.clientY);
context.stroke()
}
}
</script>
</body>
</html>
</html>
运行结果