標籤:style http io 使用 ar sp div art on
使用HTML5可以非常簡單地在canvas上實現畫圖應用,用支援html5的瀏覽器便可在下面的地區進行繪畫,要看到示範效果,請確保你的瀏覽器支援HTML5:
功能很簡單,原理其實和拖放是類似的,主要是三個事件:
- 在canvas 上綁定mousedown 事件以標誌繪畫的開始(調用moveTo 移動畫筆)澳門娛樂場
- 在document 上綁定mousemove 事件來處理繪畫時的行為(調用lineTo 以及stroke 進行繪畫)
- 在document 上綁定mouseup 事件以標誌繪畫的結束(解除綁定document 上的兩個事件)
實現時需特別注意的一點是調用moveTo 以及lineTo 方法時如何傳遞正確的座標值,這個座標值應該是游標相對於canvas 左上方的位移量,擷取時需要把canvas 相對於當前視口的位置考慮進去,getBoundingClientRect 方法則正好派上了用場(支援HTML5 的瀏覽器應該都實現了這個方法),最後用event 對象的clientX, clientY 減去getBoundingClientRect 方法返回的left, top 值即可。
下面是實現代碼:
view source print?
05 |
} else if (typeof arg == ‘string‘) { |
06 |
this.canvas = document.getElementById(arg); |
15 |
if (!this.canvas.getContext) { |
18 |
this.context = this.canvas.getContext(‘2d‘); |
19 |
this.canvas.onselectstart = function () { |
20 |
return false; //修複chrome下游標樣式的問題 |
22 |
this.canvas.onmousedown = function(event) { |
23 |
that.drawBegin(event); |
26 |
drawBegin: function(e) { |
28 |
stage_info = this.canvas.getBoundingClientRect(); |
29 |
window.getSelection ? window.getSelection().removeAllRanges() : |
30 |
document.selection.empty(); //清除文本的選中 |
32 |
e.clientX - stage_info.left, |
33 |
e.clientY - stage_info.top |
35 |
document.onmousemove = function(event) { |
38 |
document.onmouseup = this.drawEnd; |
40 |
drawing: function(e) { |
41 |
var stage_info = this.canvas.getBoundingClientRect(); |
43 |
e.clientX - stage_info.left, |
44 |
e.clientY - stage_info.top |
46 |
this.context.stroke(); |
49 |
document.onmousemove = document.onmouseup = null; |
52 |
var draw = new Draw(‘the_stage‘); |
就這樣一個簡單的鼠繪功能就完成了,不足之處也有,比如不能夠畫點。。。 我個人覺得用canvas 來做畫圖還是比較弱的,複雜一些的功能就不太好實現了,不過大家也可以嘗試下哦,比如要添加個儲存圖片的方法,定義Draw.prototype.save = function() {...},其中可調用toDataURL 方法實現。
用HTML5 Canvas做一個畫圖板