html5之canvas画图 1.写字板功能

       写字板事例:

    

      写字板分析:1.点击鼠标開始写字(onmosedown)2.按下鼠标写字(onmousemove)3.松开鼠标,停下写字(撤销onmousemove事件):

      代码:

<strong><!doctype html>  
</strong><html>  
    <head>  
        <meta charset="utf-8">  
        <title>Canvas</title>  
        <style type="text/css">  
            body {  
                margin: 0px;  
                padding: 0px;  
            }  
            #canvas {  
                margin: 0px;  
                padding: 0px;  
                border: 1px solid #000000;    
            }  
        </style>  
    </head>  
    <body>  
        <canvas id="canvas" width="400" height="400">当前浏览器不支持canvas</canvas>  
        <script type="text/javascript" src="utils.js"></script>  
        <script type="text/javascript" src="arrow.js"></script>  
        <script type="text/javascript">  
            window.onload=function(){  
            	
                var canvas=document.getElementById("canvas");  
                var context=canvas.getContext("2d"); 
               
                /*var mouse=utils.captureMousePosition(canvas); */ 
                              
                 //加入mousedown监听事件。在用户鼠标按下后開始画线。并注冊mousemove事件  
                canvas.addEventListener("mousedown",function(event){ 
                	
                    context.beginPath();  
                    context.moveTo(event.clientX, event.clientY);
                    //alert("-------------")
                    canvas.addEventListener("mousemove",onMouseMove,false);  
                },false);  
                                  
                 //在鼠标移动时划线   
                function onMouseMove(event){  
                    context.lineTo(event.clientX,event.clientY);  
                    context.stroke();     
                }  
                                //在鼠标按键松开后,注销鼠标移动事件  
                canvas.addEventListener("mouseup",function(event){  
                    canvas.removeEventListener("mousemove",onMouseMove,false);  
                },false);  
            }  
        </script>  
    </body>
 </html>



posted @ 2017-08-12 21:06  yxysuanfa  阅读(458)  评论(0编辑  收藏  举报