開發Canvas 繪畫應用(一):搭好框架

畢業汪今年要畢業啦,畢設作的是三維模型草圖檢索,年前將算法移植到移動端作了一個小應用(利用nodejs搭的服務),正好也趁此機會能夠將前端的 Canvas 好好學一下~~畢設差很少作完了,現將思路和代碼進行回顧整理,但願以最簡單的方式將核心前端部分總結並呈現。css

Canvas 繪畫應用

採用 webpackES6HTML5jQuery 構建,利用了移動端的觸摸和手勢事件,結合 Canvas,實如今移動端的繪畫功能。html

先從簡單的小繪圖功能開始實現,後面有新的功能進行迭代實現。前端

採起的CSS規範

  • 規範參考
  • OOCSS:結構(structure)與表現(skin)分離,容器(container)與內容(content)分離
  • BEM:相似於組件化的概念,獨立的元素搭積木拼接

基礎目錄結構

  • paintApp/
    • asset/
      • css/
      • img/
    • src/
      • common/
      • component/
      • app.js
    • index.html
    • package.json
    • webpack.config.js

基礎功能實現

☞ 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 上下文中設置,如 fillStylefillRectlineWidthlineJoinstrokeStyle 等。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繪畫應用(二):實現繪畫

✈ Github:paintApp

✎ 參考:

HTML5實例教程——創意畫板

使用html5 canvas製做塗鴉畫板

JS | 移動端「刮刮卡式」蒙層畫板 Canvas

相關文章
相關標籤/搜索