核心是监听mousedown、mousemove、mouseup事件,用beginpath()、moveto()、lineto()、stroke()绘线;需用getboundingclientrect()算真实坐标,mousedown中记录起点并beginpath(),mousemove中仅当isdrawing为true时lineto()和stroke(),mouseup/out时置isdrawing=false;linecap设"round"提升涂鸦感;清空用clearrect()而非canvas.width=canvas.width;高dpr屏需缩放canvas缓冲区并乘dpr处理坐标与线宽。

怎么用 <canvas></canvas> 绑定鼠标事件实现基础涂鸦
核心是监听 mousedown、mousemove、mouseup 三个事件,配合 beginPath()、moveTo()、lineTo() 和 stroke() 绘制连续线条。注意必须在 mousedown 时调用 beginPath(),否则每次 mousemove 都会从画布原点连一条线。
常见错误现象:mousemove 画出的线断断续续、出现“飞线”、或整条线从左上角开始延伸——基本都是没在 mousedown 里记下起始坐标,或没在 mousemove 中用 moveTo() 正确跳转到上一个终点。
- 用
canvas.getBoundingClientRect()计算鼠标相对于画布的真实坐标,避免缩放或外边距干扰 - 在
mousedown中记录isDrawing = true并调用ctx.beginPath()和ctx.moveTo(x, y) - 在
mousemove中仅当isDrawing为true时才执行ctx.lineTo(x, y)和ctx.stroke() -
mouseup和mouseout都要设isDrawing = false,防止鼠标移出画布后松开再移入继续画
ctx.lineWidth 和 ctx.lineCap 怎么影响涂鸦手感
线宽太小(如 1)在快速移动时容易断开;太大(如 20)又显得笨重。推荐从 3~8 开始试。更关键的是 lineCap:默认 "butt" 会让线条末端平切,相邻线段之间有明显缝隙;换成 "round" 后,每一段都带圆头,拼接更自然,涂鸦感立刻提升。
-
ctx.lineCap = "round"是最常用选择,尤其适合手绘风格 -
ctx.lineJoin = "round"可同时改善拐角处的连接效果 - 不要在每次
mousemove中重复设置lineWidth或strokeStyle,只在初始化或用户切换工具时设一次 - 移动端需额外处理
touchstart/touchmove,且touches[0]坐标也要过getBoundingClientRect()
清空画布为什么不能只用 canvas.width = canvas.width
这句看似能重置,但会强制重设 canvas 内部缓冲区,导致所有 CSS 缩放、transform 样式丢失,还可能触发重排。更严重的是:如果 canvas 被设了 width/height CSS 属性(而非内联属性),canvas.width = canvas.width 会让画布内容被拉伸或压缩。
- 正确做法是用
ctx.clearRect(0, 0, canvas.width, canvas.height) - 如果需要保留背景色,再紧接着填一层
ctx.fillStyle+ctx.fillRect() - 若想支持“撤销”,别清空,而是把每次笔画存为路径数组,重绘时遍历重画
- 注意:清空后无需再调用
beginPath(),它只影响后续路径构建,和画布像素无关
为什么在高 DPI 屏幕上画线发虚或变细
因为 canvas 的像素密度(devicePixelRatio)和 CSS 显示尺寸不匹配。比如 retina 屏 devicePixelRatio=2,但你只按 CSS 宽高(如 500×300)设置了 canvas 尺寸,实际渲染缓冲只有 500×300 像素,被拉伸到 1000×600 物理像素,自然模糊。
- 获取
const dpr = window.devicePixelRatio || 1 - 将 canvas 的
width和height属性设为CSS宽 × dpr和CSS高 × dpr - 再用 CSS 把 canvas 宽高设回原始值(如
style="width:500px;height:300px;") - 最后记得对所有坐标乘以
dpr,包括鼠标位置和lineWidth(否则线宽还是 1px 物理像素)
这个缩放适配最容易被跳过,一上线就在 MacBook 或 iPhone 上发现线条糊成一片,得回头补。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











