Canvas - 捕捉手寫軌跡

入門 HTML5 應該馬上就會接觸到 Canvas ,而 Canvas 最簡單的應用,就是搭配滑鼠事件的手寫軌跡捕捉,例如以下的範例:


用滑鼠直接在上面按住拖曳,就會出現手寫的效果(IE看不到黑色畫板,請更換瀏覽器),按一下「清空」按鈕即可將畫面清除。這個程式很簡單,先建立支援手寫軌跡捕捉功能的 <canvas> 標籤:

<body >
<canvas id="pCanvas" width=560;  height=360; 
        onmousedown="mousedownandler(event)" 
        onmousemove="mousemoveandler(event)"
        onmouseup="mouseupHandler(event)"
        style="cursor:pointer;background:black;"       
         >
</canvas>
<hr />
<button onclick="clearCanvas()" style="width:200px;" >清空</button>
</body>

由於要捕捉使用者的滑鼠操作,因此必須分別設定相關的滑鼠事件屬性,最後配置的按鈕,提供清空畫面的功能,執行的函式為 clearCanvas() 。首先是使用者按下滑鼠的部份,取得目前的座標位置,並設定所要描繪的線條樣式:

function mousedownandler(e) {
            var x = e.clientX;
            var y = e.clientY;
            context.beginPath();
            context.lineWidth = 12;
            context.strokeStyle = 'white';
            context.moveTo(x, y);
            paint = true;
 }

接下來是捕捉滑鼠移動的部份,onmousemove 事件回應函式如下,其中取得目前滑鼠的作標位置,然後調用 lineTo() 方法,移動至座標點,再調用 stroke() 將線條描繪出來。

function mousemoveandler(e) {
            if (paint) {
                var x = e.clientX;
                var y = e.clientY;
                context.lineTo(x, y);
                context.stroke();
            }
 }

完成相關事件的捕捉,即可建立想要的效果,以下是完整的程式碼,請自行嘗試。

<!DOCTYPE html>
<html >
<head>
    <title></title>
    <script>
        var paintpoints = new Array();
        var paintpoints_content = new Array();
        var canvas;
        var context;
        var paint = false;
        window.onload = function () {
            canvas = document.getElementById("pCanvas");
            context = canvas.getContext("2d");
        };
        function mousedownandler(e) {
            var x = e.clientX;
            var y = e.clientY;
            context.beginPath();
            context.lineWidth = 12;
            context.strokeStyle = 'white';
            context.moveTo(x, y);
            paint = true;
        }
        function mousemoveandler(e) {
            if (paint) {
                var x = e.clientX;
                var y = e.clientY;
                context.lineTo(x, y);
                context.stroke();
            }
        }
        function mouseupHandler(e) {
            paint = false;
        }
        function clearCanvas() {
            context.clearRect(0, 0, canvas.width, canvas.height);
        }
    </script>
</head>
<body >
<canvas id="pCanvas" width=560;  height=360; 
        onmousedown="mousedownandler(event)" 
        onmousemove="mousemoveandler(event)"
        onmouseup="mouseupHandler(event)"
        style="cursor:pointer;background:black;"       
         >
</canvas>
<hr />
<button onclick="clearCanvas()" style="width:200px;" >清空</button>
</body>
</html>

沒有留言: