在board.js
中,抽象了桌面端和移动端的鼠标事件逻辑,使用startPoint、lastPoint、endPoint来更新当前点的状态,并且调用当前选定的shape进行绘图。
painting
变量控制着是否正在绘图
的语义,只有当在canvas上点击后才会开始绘图。
正常逻辑中,mousemove
事件中执行绘图操作。mouseup
事件中,会结束绘图(painting
变量设置为否),保存绘图历史。
桌面端鼠标移出canvas外,是通过mouseout
事件判断的,就会结束绘图(painting
变量设置为否),保存绘图历史。此时,鼠标的mousemove
、mouseup
事件都会先判断不在绘图中,也就不会触发相关函数。
移动端鼠标移出canvas外,是通过鼠标坐标是否在canvas内判断的,mousemove
事件中,鼠标移出canvas外后,就会结束绘图(painting
变量设置为否),保存绘图历史。此时,鼠标的mousemove
、mouseup
事件都会先判断不在绘图中,也就不会触发相关函数。
initDrawEvents() { this.startPoint = { x: undefined, y: undefined } this.lastPoint = { x: undefined, y: undefined }; this.endPoint = { 'x': undefined, 'y': undefined }; let painting = false; // 鼠标按下事件 this.template.canvasEle.addEventListener(Utils.nameMap.dragStart, (e) => { // console.log("onmousedown"); e.preventDefault(); painting = true; this.startPoint = this._getPoint(e); this.lastPoint = this.startPoint; this.shape.startDraw(); }); // 鼠标移动事件 this.template.canvasEle.addEventListener(Utils.nameMap.dragMove, (e) => { // console.log("onmousemove"); e.preventDefault(); if (!painting) return; this.endPoint = this._getPoint(e); // 移动端没有 mouseout 事件,但绑定在 canvasEle 的 touchmove 方法,在触摸点离开 canvasEle 仍然会触发 // 可以用来检测,触摸点是否移出了 canvasEle if (Utils.isMobile && this._outCanvas(this.endPoint)) { // console.log("outCanvas"); painting = false; if (this.shape.endDraw()) { this.drawDone(); } } else { this.shape.drawing(); this.lastPoint = this.endPoint; } }); // 鼠标松开事件 this.template.canvasEle.addEventListener(Utils.nameMap.dragEnd, (e) => { // console.log("onmouseup"); e.preventDefault(); if (!painting) return; painting = false; // 移动端的 touchend 事件是获取不到 e.touches[0] 的。直接使用 touchmove 事件的最后触摸点 // this.endPoint = this._getPoint(e); if (this.shape.endDraw()) { this.drawDone(); } }); this.template.canvasEle.addEventListener('mouseout', (e) => { // console.log("mouseout"); e.preventDefault(); if (!painting) return; painting = false; if (this.shape.endDraw()) { this.drawDone(); } }); } _outCanvas(point) { if (point.x > 0 && point.x < this.template.canvasEle.width && point.y > 0 && point.y < this.template.canvasEle.height) { return false; } else { return true; } }
反馈:您觉得本站怎么样?(此评价不会公开,也不会对博主产生任何实际利益。)
- 非常优秀
- 可以
- 一般
- 垃圾
- 超级恶心