-
Notifications
You must be signed in to change notification settings - Fork 18
/
scratchcard.min.js
1 lines (1 loc) · 2.6 KB
/
scratchcard.min.js
1
"use strict";var ScratchCard=function(t){return this.canvasID=t.id,this.width=t.brushSize,this.shape=t.lineJoin,this.clearRequirement=t.percentRequired,this.color=t.fillColor,this.lastX,this.lastY,this.init(this.canvasID),this.can};ScratchCard.prototype.init=function(t){this.pressed=!1,this.can=document.getElementById(t),this.ctx=this.can.getContext("2d");var e=this.can.getBoundingClientRect();this.offset={top:e.top+document.body.scrollTop,left:e.left+document.body.scrollLeft},this.can.addEventListener("mousedown",this.mouseDown.bind(this),!1),this.can.addEventListener("mousemove",this.mouseMove.bind(this),!1),this.can.addEventListener("mouseup",this.mouseUp.bind(this),!1),this.can.addEventListener("touchstart",this.touchDown.bind(this),!1),this.can.addEventListener("touchmove",this.touchMove.bind(this),!0),this.can.addEventListener("touchend",this.touchUp.bind(this),!1),this.can.addEventListener("touchcancel",this.touchUp.bind(this),!1),this.reset()},ScratchCard.prototype.mouseDown=function(t){this.pressed=!0;var e=t.pageX-this.offset.left,s=t.pageY-this.offset.top;this.draw(e,s,!1)},ScratchCard.prototype.mouseMove=function(t){if(this.pressed){var e=t.pageX-this.offset.left,s=t.pageY-this.offset.top;this.draw(e,s,!0)}},ScratchCard.prototype.mouseUp=function(){this.pressed=!1},ScratchCard.prototype.touchDown=function(t){t.preventDefault(),this.pressed=!0;var e=t.targetTouches[0].pageX-this.offset.left,s=t.targetTouches[0].pageY-this.offset.top;this.draw(e,s,!1)},ScratchCard.prototype.touchMove=function(t){if(t.preventDefault(),this.pressed){var e=t.targetTouches[0].pageX-this.offset.left,s=t.targetTouches[0].pageY-this.offset.top;this.draw(e,s,!0)}},ScratchCard.prototype.touchUp=function(){this.pressed=!1},ScratchCard.prototype.draw=function(t,e,s){s&&(this.ctx.beginPath(),this.ctx.globalCompositeOperation="destination-out",this.ctx.strokeStyle="rgba(0, 0, 0, 1)",this.ctx.lineWidth=this.width,this.ctx.lineJoin=this.shape,this.ctx.moveTo(this.lastX,this.lastY),this.ctx.lineTo(t,e),this.ctx.closePath(),this.ctx.stroke()),this.lastX=t,this.lastY=e;var i=this.calcPixels(25);this.clearPercentage(i)},ScratchCard.prototype.calcPixels=function(t){for(var e=this.ctx.getImageData(0,0,this.can.width,this.can.height),s=e.data,i=s.length,h=i/t,o=0,a=o;i>a;a+=t)0===parseInt(s[a])&&o++;return Math.round(o/h*100)},ScratchCard.prototype.clearPercentage=function(t){if(t===this.clearRequirement){var e=new Event("success");this.can.dispatchEvent(e)}},ScratchCard.prototype.reset=function(){this.ctx.globalCompositeOperation="source-over",this.ctx.fillStyle=this.color,this.ctx.fillRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height)};