效果图
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#canvas {
border: 1px solid red;
}
</style>
</head>
<body>
<canvas id="canvas" width="800" height="800"></canvas>
</body>
</html>
<script>
// 线条宽度
let strokeWidth = 5;
// 线条颜色
let strokeColor = 'red';
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
// 线条末端添加圆形线帽,减少线条的生硬感
ctx.lineCap = 'round';
// 当两条线条交汇时,创建圆形边角
ctx.lineJoin = 'round';
ctx.lineWidth = strokeWidth;
ctx.strokeStyle = strokeColor;
// 利用阴影,消除锯齿
ctx.shadowBlur = 1;
ctx.shadowColor = strokeColor;
let drawStatus = false;
canvas.addEventListener('mousedown', function(e){
drawStatus = true;
ctx.moveTo(e.offsetX, e.offsetY);
startX = e.offsetX;
startY = e.offsetY;
});
canvas.addEventListener('mousemove', function(e) {
if (!drawStatus) {
return;
}
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
})
canvas.addEventListener('mouseup', function(e) {
drawStatus = false;
console.log('out');
})
</script>