1. 程式人生 > >javascript 之一個簡單的畫圖demo

javascript 之一個簡單的畫圖demo

這是一個用javascript 在canvas 上實現的簡單的畫圖應用,用支援html5 的瀏覽器可以看到如下效果:

功能很簡單,原理其實和拖放是類似的,主要是三個事件:

1. 在canvas 上繫結mousedown 事件以標誌繪畫的開始(呼叫moveTo 移動畫筆)

2. 在document 上繫結mousemove 事件來處理繪畫時的行為(呼叫lineTo 以及stroke 進行繪畫)

3. 在document 上繫結mouseup 事件以標誌繪畫的結束(解綁document 上的兩個事件)

實現時需特別注意的一點是呼叫moveTo 以及lineTo 方法時如何傳遞正確的座標值,這個座標值應該是游標相對於canvas 左上角的偏移量,獲取時需要把canvas 相對於當前視口的位置考慮進去,getBoundingClientRect 方法則正好派上了用場(支援HTML5 的瀏覽器應該都實現了這個方法),最後用event 物件的clientX, clientY 減去getBoundingClientRect 方法返回的left, top 值即可。

就這樣一個簡單的鼠繪功能就完成了,不足之處也有,比如不能夠畫點。。。 我個人覺得用canvas 來做畫圖還是比較弱的,複雜一些的功能就不太好實現了,不過大家也可以嘗試下哦,比如要添加個儲存圖片的方法,定義Draw.prototype.save = function() {...},其中可呼叫toDataURL 方法實現。

最後附上原始碼:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>draw demo</title>
</head>
<body>

<canvas id="the_stage" width="600" height="400" style="border:1px solid #999;">您的瀏覽器不支援canvas!</canvas>

<script>
function Draw(arg) {
    if (arg.nodeType) {
        this.canvas = arg;
    } else if (typeof arg == 'string') {
        this.canvas = document.getElementById(arg);
    } else {
        return;
    }
    this.init();
}
Draw.prototype = {
    init: function() {
        var that = this;
        if (!this.canvas.getContext) {
            return;
        }
        this.context = this.canvas.getContext('2d');
        this.canvas.onselectstart = function () {
            return false;  //修復chrome下游標樣式的問題
        };
        this.canvas.onmousedown = function(event) {
            that.drawBegin(event);
        };
    },
    drawBegin: function(e) {
        var that = this,
            stage_info = this.canvas.getBoundingClientRect();
        window.getSelection ? window.getSelection().removeAllRanges() :
                                document.selection.empty();  //清除文字的選中
        this.context.moveTo(
            e.clientX - stage_info.left,
            e.clientY - stage_info.top
        );
        document.onmousemove = function(event) {
            that.drawing(event);
        };
        document.onmouseup = this.drawEnd;
    },
    drawing: function(e) {
        var stage_info = this.canvas.getBoundingClientRect();
        this.context.lineTo(
            e.clientX - stage_info.left,
            e.clientY - stage_info.top
        );
        this.context.stroke();
    },
    drawEnd: function() {
        document.onmousemove = document.onmouseup = null;
    }
};
var draw = new Draw('the_stage');
</script>
</body>
</html>

原文連結:http://www.cnblogs.com/eric6/archive/2011/07/26/2116893.html