畢業汪今年要畢業啦,畢設做的是三維模型草圖檢索,年前將算法移植到移動端做了一個小應用(利用nodejs搭的服務),正好也趁此機會可以將前端的 Canvas 好好學一下~~畢設差不多做完了,現將思路和代碼進行回顧整理,希望以最簡單的方式將核心前端部分總結並呈現。
Canvas 繪畫應用
采用 webpack
、ES6
、HTML5
、jQuery
構建,利用了移動端的觸摸和手勢事件,結合 Canvas
,實現在移動端的繪畫功能。
先從簡單的小繪圖功能開始實現,后面有新的功能進行迭代實現。
采取的CSS規范
基礎目錄結構
- paintApp/
- asset/
- css/
- img/
- src/
- common/
- component/
- app.js
- index.html
- package.json
- webpack.config.js
- asset/
基礎功能實現
☞ index.html
<canvas class="painter" id="js-cva">A drawing of something</canvas>
☞ painter.js
① 獲取canvas及上下文
// 初始化選擇器
initSelectors() {
this.cva = document.getElementById('js-cva');
this.ctx = this.cva.getContext('2d');
return this;
}
② 設置繪圖板
// 屬性設置
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
等。
③ 監聽觸摸事件
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繪畫應用(二):實現繪畫