我画你猜(一)

----- 最近同事老拉着玩一个游戏《我画你猜》,非常好玩,于是作为码农尝试着自己做个。

先实现画布的简单功能;简单的把功能封装了两个类

(1)元素类,也是整个画画功能的进入点

/*****元素类*****/
function DrawElement(cavId,clearId,eraserId){
    this.ele = document.getElementById(cavId);
    this.clearBnt = document.getElementById(clearId);
    this.eraserBnt = document.getElementById(eraserId);
    //是否是橡皮擦模式
    this.isEraser = false;
    this.draw = new Draw(this.ele);
    var that = this;
    //获取画笔的x和y
    this.getXY = function(xOrY){
        if(xOrY === 'x') return this.pageX - that.ele.offsetLeft;
        return this.pageY - that.ele.offsetTop;
    }
}

DrawElement.prototype.init = function(){
    var ele = this.ele;
    var draw = this.draw;
    var getXY = this.getXY;
    var that = this;
    ele.onmousedown = function(e){
        var ev = e || window.event;
        draw.drawBegin(getXY.call(ev,'x'),getXY.call(ev));
    };
    ele.onmousemove = function(e){
        var ev = e || window.event;
        if(that.isEraser){
            draw.clear(getXY.call(ev,'x'),getXY.call(ev));
        }else{
            draw.drawMiddle(getXY.call(ev,'x'),getXY.call(ev));
        }
    };
    ele.onmouseup = function(){
        draw.drawEnd();
    };
    ele.onmouseleave = function(){
        draw.drawEnd();
    };
    //清除画布
    this.clearBnt.onclick = function(){
        draw.clearAll();
    };
    //进入橡皮擦模式
    this.eraserBnt.onclick = function(e){
        var ev = e || window.event;
        that.isEraser = !that.isEraser;
        ev.target.innerText = that.isEraser?"继续画画":"橡皮擦"
    };
}

(2)画画类

/*****画画类*****/
function Draw(cvs,isBegin){
    this.begin = isBegin || false;
    this.cvs = cvs;
    this.cvx = cvs.getContext("2d");
}

Draw.prototype.drawBegin = function(x,y){
    this.begin = true;
    var cvx = this.cvx;
    cvx.beginPath();
    cvx.moveTo(x, y);
}

Draw.prototype.drawMiddle = function(x,y){
    var cvx = this.cvx;
    if(this.begin){
        cvx.lineTo(x, y);
        cvx.stroke();
    }
}

Draw.prototype.drawEnd = function(){
    this.begin = false;
}

//橡皮擦功能
Draw.prototype.clear = function(x,y){
    if(this.begin){
        this.cvx.clearRect(x,y,20,20);
    }
}

//清空画布
Draw.prototype.clearAll = function(){
    this.cvx.clearRect(0,0,this.cvs.clientWidth,this.cvs.clientHeight);
}

 

(3)然后HTML

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <canvas width="600" height="600" id="cvs"></canvas>
    <button id="clear-all">清空画布</button>
    <button id="clear">橡皮擦</button>
    <script src="/javascripts/index.js"></script>
    <script>
      window.onload = function(){
        /**************画布id  清除画布id   橡皮擦id*****/
        new DrawElement('cvs','clear-all','clear').init();
      };
    </script>
  </body>
</html>

 

简单调试后得到以下效果

 

posted @ 2017-08-09 23:02  longorYang  阅读(320)  评论(0编辑  收藏  举报