Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 HTML5 Canvas 實作手寫板的小例子

最近專案終於輕鬆了些,我便抱著學習的心態研讀了 HTML Canvas 2D Context 的相關內容。回想從前曾在 Android 上做過原筆跡手寫的功能,於是就興起念頭,想試著在 HTML5 裡也簡單實作一番。摸索之下完成了這個 demo,以下是在 Google Chrome 13.0 版本上的呈現效果。

下面附上程式碼,純粹為了學習,尚未做過優化,權充範例:

註:必須在支援 HTML5 的瀏覽器上執行,才能看到效果。

<html>
   <head>
   <title>write demo</title>
   </head>
   <body>
   <canvas width="800" height="450"></canvas>
   <script>
   var canvas = document.getElementsByTagName('canvas')[0];
   canvas.addEventListener('mousemove', onMouseMove, false);
   canvas.addEventListener('mousedown', onMouseDown, false);
   canvas.addEventListener('mouseup', onMouseUp, false);
   var context = canvas.getContext('2d');
   var linex = new Array();
   var liney = new Array();
   var linen = new Array();
   var lastX = -1;
   var lastY = -1;
   var hue = 0;
   var flag = 0;
   function onMouseMove(evt) {
     if (flag == 1) {
        linex.push(evt.layerX);
        liney.push(evt.layerY);
        linen.push(1);
        context.save();
        context.translate(context.canvas.width/2, context.canvas.height/2);
        context.translate(-context.canvas.width/2, -context.canvas.height/2);
        context.beginPath();
        context.lineWidth = 5 + Math.random() * 10;
        for (var i=1;i<linex.length;i++) {
            lastX = linex[i];
            lastY = liney[i];
            if (linen[i] == 0) {
               context.moveTo(lastX,lastY);
            } else {
               context.lineTo(lastX,lastY);
            }
        }
        hue = hue + 10 * Math.random();
        context.strokeStyle = 'hsl(' + hue + ', 50%, 50%)';
        context.shadowColor = 'white';
        context.shadowBlur = 10;
        context.stroke();
        context.restore();
     }
   }
   function onMouseDown(evt) {
     flag = 1;
     linex.push(evt.layerX);
     liney.push(evt.layerY);
     linen.push(0);
   }
   function onMouseUp(evt) {
     flag = 0;
     linex.push(evt.layerX);
     liney.push(evt.layerY);
     linen.push(0);
   }
   </script>
   </body>
</html>

Copyright © Linux教程網 All Rights Reserved