刮刮乐(三种方式)

by miya lee

HTML

<div class="scratcher">
  <img class="img" src="http://www.lvyouw.net/t/pic/a46/a7a/8ebaf274857203e047308470d5.jpg">
  <canvas class="canvas" width="500px" height="150px" id="canvas"></canvas>
</div>

CSS

.scratcher {
  width: 500px;
  height: 150px;
  position: absolute;
  margin: auto;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: hidden;
}
.img {
  position: absolute;
  top: -240px;
  left: -60px;
}
.canvas {
  position: absolute;
}

JavaScript

function scratcher() {
  return this.init();
}

scratcher.prototype = {
  init: function() {
    this.canvas = document.getElementById('canvas');
    this.ctx = this.canvas.getContext('2d');
    this.flag = true;
    
    this.draw();
    this.bind();
    return this;
  },
  
  draw: function() {
    this.ctx.fillStyle = "#ccc";
    this.ctx.fillRect(0, 0, canvas.width, canvas.height);
  },
  
  scratchHandle: function(e) {
    var self = this,
        evt = e || window.event,
        canvas_location = this.canvas.getBoundingClientRect(),
        client_x = evt.clientX || evt.touches[0].clientX,
        client_y = evt.clientY || evt.touches[0].clientY,
        x = client_x - canvas_location.left,
        y = client_y - canvas_location.top;

    //方式一
    // this.ctx.clearRect(x-25, y-25, 50, 50);
    
    //方式二
    // this.ctx.globalCompositeOperation = 'destination-out';
    // this.ctx.beginPath();
    // this.ctx.arc(x, y, 25, 0, Math.PI*2, false);
    // this.ctx.fillStyle = 'rgba(0, 0, 0, 1)';
    // this.ctx.fill();
    
    //方式三
    this.ctx.globalCompositeOperation = 'destination-out';
    this.ctx.lineWidth = 40;
    this.ctx.lineCap = "round";
    
    if(this.flag) {
      self.ctx.beginPath();
      self.ctx.moveTo(x, y);
      self.flag = false;
    }
    this.ctx.lineTo(x, y);
    this.ctx.stroke();
  },
  
  bind: function() {
    var self = this;
    
    this.canvas.onmousedown = function(){
      self.canvas.onmousemove = self.scratchHandle.bind(self);
    }

    this.canvas.onmouseup = function() {
      self.canvas.onmousemove = null;
      self.flag = true;
    }

    this.canvas.addEventListener('touchmove', self.scratchHandle.bind(self), false);

    this.canvas.addEventListener('touchend', function(){
      self.canvas.removeEventListener('touchmove', self.scratchHandle.bind(self), false);
      self.flag = true;
    }, false);
  }
}

new scratcher();