畢業汪今年要畢業啦,畢設作的是三維模型草圖檢索,年前將算法移植到移動端作了一個小應用(利用nodejs搭的服務),正好也趁此機會能夠將前端的 Canvas 好好學一下~~畢設差很少作完了,現將思路和代碼進行回顧整理,但願以最簡單的方式將核心前端部分總結並呈現。css
採用 webpack
、ES6
、HTML5
、jQuery
構建,利用了移動端的觸摸和手勢事件,結合 Canvas
,實如今移動端的繪畫功能。html
先從簡單的小繪圖功能開始實現,後面有新的功能進行迭代實現。前端
☞ index.htmlhtml5
<canvas class="painter" id="js-cva">A drawing of something</canvas>
☞ painter.jsnode
① 獲取canvas及上下文webpack
// 初始化選擇器 initSelectors() { this.cva = document.getElementById('js-cva'); this.ctx = this.cva.getContext('2d'); return this; }
② 設置繪圖板git
// 屬性設置 setConfig() { this.config = { cvaW: 800, cvaH: 600, cvaBg: '#fff', lineWidth: 2, lineJoin: 'round', strokeStyle: 'red' }; return this; } // 畫板寬高設置 // 注意此處不能在 css 中設置,像素會失真,會致使不能獲取正確的座標 setCvaWH() { this.cva.setAttribute('width', this.config.cvaW); this.cva.setAttribute('height', this.config.cvaH); return this; } // 畫板背景設置 setCvaBg() { this.ctx.fillStyle = this.config.cvaBg; this.ctx.fillRect(0, 0, this.config.cvaW, this.config.cvaH); return this; } // 畫筆設置 setPen() { this.ctx.lineWidth = this.config.lineWidth; this.ctx.lineJoin = this.config.lineJoin; this.ctx.strokeStyle = this.config.strokeStyle; return this; }
設置樣式均在 this.ctx 上下文中設置,如
fillStyle
、fillRect
、lineWidth
、lineJoin
、strokeStyle
等。github
③ 監聽觸摸事件web
initEvents() { this._touchListen('touchstart'); this._touchListen('touchmove'); this._touchListen('touchend'); } _touchListen(event) { this.cva.addEventListener(event, $.proxy(this.touchF, this), false); }
移動端的觸摸事件以下(摘自《JavaScript 高級程序設計》):算法
touchstart
:當手指觸摸屏幕時觸發;即便有一個手指放在了屏幕上也觸發。touchmove
:當手指在屏幕上滑動時連續地觸發。在這個事件發生期間,調用 preventDefault()
能夠阻止滾動touchend
:當手指東屏幕上移開時觸發。toucncancle
:當系統中止跟蹤觸摸時觸發。關於此事件的確切觸發時間,文檔中沒有明確說明。④ 事件處理函數(★重點)
touchF(e) { e.preventDefault(); // 阻止瀏覽器默認行爲 switch (e.type) { case 'touchstart': break; case 'touchmove': break; case 'touchend': break; } }
基礎框架有了,事件監聽也實現了,接下來就是獲取觸摸點的座標,實現繪畫功能了,請繼續閱讀 開發Canvas繪畫應用(二):實現繪畫