今天分享一个好玩的玩意儿,就是小时候最喜欢玩的刮刮卡,不同的是,这个刮刮卡用HTML5 canvas绘制。
刮刮卡主要由两层canvas绘制,底层放置随机数,顶层放置图片,限制每天只能刮三次;
查看效果
两层canvas布局
刮刮乐
刮刮乐小游戏
温馨提示:每人每天三次刮刮乐机会哦~
绘制底层canvas
var useNumber=0,
luckNumber=[],
mousedown,
w = 200,
h = 100;
var bottomCanvas = document.querySelector("#bottom");
var topCanvas = document.querySelector('#top');
topCanvas.width = bottomCanvas.width = w;
topCanvas.height = bottomCanvas.height = h;
var ctxBot = bottomCanvas.getContext("2d");
var ctxTop = topCanvas.getContext('2d');
bottomCanvas.style.background = "#f40";
ctxBot.font = "30px 微软雅黑";
function drawBot(){
//清除区域,为了点击再来一次进行页面重绘
ctxBot.clearRect(0, 0, w, h);
luckNumber.push(random());
//fillText(填充)实心数字 改为strokeText(描边)为空心数字
ctxBot.fillText( luckNumber[luckNumber.length-1],70,55);
}
//获取1-1000随机数
function random(){
return Math.ceil(Math.random()*1000);
}
绘制顶层canvas
var img = new Image();
img.src = "img/img.jpg";
img.onload = function (){
drawBot();
drawTop();
}
function drawTop(){
ctxTop.canvas.style.opacity = 1;
ctxTop.drawImage(img , 0 , 0 , w , h);
//判断当前是否为第一次刮开,不是则清除上一次区域
if(ctxTop.globalCompositeOperation != 'destination-out'){
ctxTop.globalCompositeOperation = 'destination-out';
}else{
ctxTop.clearRect(0, 0, w, h);
}
}
鼠标移动开始刮图层
//鼠标移动开始刮图层
topCanvas.addEventListener('touchstart', eventDown);
topCanvas.addEventListener('touchend', eventUp);
topCanvas.addEventListener('touchmove', eventMove);
topCanvas.addEventListener('mousedown', eventDown);
document.addEventListener('mouseup', eventUp);
topCanvas.addEventListener('mousemove', eventMove);
function eventDown(ev){
ev = ev || event;
ev.preventDefault();
mousedown=true;
}
function eventUp(ev){
ev = ev || event;
ev.preventDefault();
mousedown=false;
}
function eventMove(ev){
ev = ev || event;
ev.preventDefault();
if(mousedown) {
if(ev.changedTouches){
ev=ev.changedTouches[ev.changedTouches.length-1];
}
var x = ev.pageX - this.offsetLeft;
var y = ev.pageY - this.offsetTop;
ctxTop.beginPath();
ctxTop.arc(x, y, 10, 0, Math.PI * 2);
ctxTop.fill();
alertInfo();
}
}
判断刮开区域
// 判断刮开区域大于80%时,顶层canvas消失,显示底层数据
function alertInfo(){
var data=ctxTop.getImageData(0,0,w,h).data;
for(var i=0 , j=0 ; i< data.length;i+=4){
if(data[i] && data[i+1] && data[i+2] && data[i+3]){
j++;
}
}
if(j <= w*h*0.2){
ctxTop.globalCompositeOperation = 'destination-over';
ctxTop.canvas.style.opacity = 0;
document.querySelector("button").style.display="block";
alert(luckNumber[luckNumber.length-1]);
}
}
再来一次
//点击再来一次进行页面重绘next
function next(){
useNumber++;
//判断当前点击次数
if(useNumber>2){
alert("今日抽奖次数用完啦~今日所抽号码为"+luckNumber);
document.querySelector("button").disabled = true;
}else{
drawBot();
drawTop();
}
}