JS canvas 画板 撤销

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <style type="text/css">
        #button{
            width: 60px;
            height: 20px;
        }
    </style>
    
</head>
<body>
    <canvas id="canvas" width="600px" height="400px" style="background: #DBDDDF; "></canvas>
    <input type="button" value="撤销" id="button">


    <script type="text/javascript">
        var canvas=document.getElementById('canvas');
        var cext=canvas.getContext('2d');

        cext.strokeStyle="black";
        cext.lineWidth=2;
        cext.fillStyle="black";


        function getStyles(obj){//兼容FF,IE10; IE9及以下未测试
            return document.defaultView.getComputedStyle(obj);
        } 
        function getCanvasPos(canvas,e)  
        {//获取鼠标在canvas上的坐标  
            var rect = canvas.getBoundingClientRect(); 
            var leftB = parseInt(getStyles(canvas).borderLeftWidth);//获取的是样式,需要转换为数值
            var topB = parseInt(getStyles(canvas).borderTopWidth);
            return {   
                x: (e.clientX - rect.left) - leftB,  
                y: (e.clientY - rect.top) - topB 
           };  
        } 
        
        
        var restorePoint = {};
        var shuzu=[];
        var h=0;
        var x1,x2,newx,newy;

        canvas.onmousedown=function (e) {
            restorePoint = cext.getImageData(0, 0, canvas.width, canvas.height);
            x1=getCanvasPos(canvas,e).x;
            x2=getCanvasPos(canvas,e).y;
            canvas.onmousemove=function(e){
                cext.putImageData(restorePoint, 0, 0);
                newx=getCanvasPos(canvas,e).x;
                newy=getCanvasPos(canvas,e).y;
                cext.beginPath();
                cext.moveTo(x1,x2);
                cext.lineTo(newx,newy);
                cext.stroke();
                cext.closePath();
            }
        }


        canvas.onmouseup=function(){
            shuzu[h] = restorePoint;
            h++;
            canvas.onmousemove=null;
           
        }

        document.getElementById("button").onmousedown=function(){
            restorePoint = shuzu[h-1];
                    cext.putImageData(restorePoint, 0, 0);
                    h--;
        }
    </script>
</body>
</html>

 

posted on 2018-12-11 20:10  huas_psw  阅读(760)  评论(0编辑  收藏  举报