DIV CSS 佈局教程網

結合 HTML5 Canvas 實現功能完整的塗鴉板
編輯:關於JavaScript     

HTML5 的 Canvas 為瀏覽器帶來了強大的繪圖能力。本文分享一個以純 JavaScript 搭配 Canvas 打造的塗鴉板,支援調整畫筆顏色、粗細、橡皮擦、清除、撤銷,還能把作品導出為圖片,非常適合練習 Canvas 的各種 API。

功能亮點

這個塗鴉板具備:多種顏色選擇、三種畫筆粗細、橡皮擦、清除畫布、撤銷、以及導出圖片路徑等功能,並同時兼容桌面滑鼠與手持設備的觸摸操作。

畫筆與座標記錄

核心思路是用陣列記錄滑鼠移動軌跡的座標,再透過 Canvas 的路徑 API 繪製:

movePoint: function(x, y, dragging) {
  this.x.push(x);
  this.y.push(y);
  this.clickDrag.push(y);
}

drawPoint: function() {
  for(var i=0; i<this.x.length; i++){
    this.cxt.beginPath();
    if(this.clickDrag[i] && i){ this.cxt.moveTo(this.x[i-1], this.y[i-1]); }
    else{ this.cxt.moveTo(this.x[i]-1, this.y[i]); }
    this.cxt.lineTo(this.x[i], this.y[i]);
    this.cxt.closePath();
    this.cxt.stroke();
  }
}

橡皮擦的實現

橡皮擦巧妙地運用了 globalCompositeOperation 屬性,將繪圖模式設為 destination-out,就能擦除已繪製的內容:

resetEraser: function(_x, _y, touch) {
  var t = this;
  t.cxt.globalCompositeOperation = "destination-out";
  t.cxt.beginPath();
  t.cxt.arc(_x, _y, t.eraserRadius, 0, Math.PI * 2);
  t.cxt.strokeStyle = "rgba(250,250,250,0)";
  t.cxt.fill();
  t.cxt.globalCompositeOperation = "source-over"
}

觸摸設備相容

為了支援手機,程式會判斷是否為觸摸設備,並據此選擇不同的事件名稱:

this.touch = ("createTouch" in document);
this.StartEvent = this.touch ? "touchstart" : "mousedown";
this.MoveEvent = this.touch ? "touchmove" : "mousemove";
this.EndEvent = this.touch ? "touchend" : "mouseup";

導出圖片

最後,透過 Canvas 的 toDataURL() 方法,就能把畫布內容轉成圖片編碼:

getUrl: function() {
  this.$("html").innerHTML = this.canvas.toDataURL();
}

這整個範例把 Canvas 的繪圖、合成模式、座標處理與觸摸事件整合在一起,是一個很值得深入研究的入門級實作專案。使用前請確認瀏覽器已支援 HTML5 Canvas。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved