canvas实现刮刮卡效果

实现步骤:

  1. 设置页面背景图,即刮刮卡底部图片
  2. 绘制canvas 刮刮卡顶部图片drawImage
  3. 绑定事件 addEventListener  touchstart、touchmove

完整代码:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no">
<title>02</title>
<style type="text/css">
* {
padding: 0;
margin: 0;
}
html, body {
height: 100%;
overflow: hidden;
}
#wrap {
height: 100%;
overflow: hidden;
}
#wrap > div {
height: 100%;
background-image: url(1.jpg);
background-repeat: no-repeat;
background-size: 100% 100%;
}
canvas {
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div id="wrap">
<div></div>
<canvas></canvas>
</div>
<script type="text/javascript">
window.onload = function(){
var canvas = document.querySelector("canvas");
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
if(canvas.getContext){
var ctx = canvas.getContext("2d");
var img = new Image();
img.src = "2.jpg";
img.onload = function(){
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
canvas.addEventListener("touchstart", function(ev){
ev = ev || event;
var touchC = ev.changedTouches[0];
var x = touchC.clientX;
var y = touchC.clientY;
ctx.save();
ctx.beginPath();
ctx.globalCompositeOperation = "destination-out";
ctx.arc(x,y,25,0,360*Math.PI/180);
ctx.fill();
ctx.restore();
}) canvas.addEventListener("touchmove", function(ev){
ev = ev || event;
var touchC = ev.changedTouches[0];
var x = touchC.clientX;
var y = touchC.clientY;
ctx.save();
ctx.beginPath();
ctx.globalCompositeOperation = "destination-out";
ctx.arc(x,y,25,0,360*Math.PI/180);
ctx.fill();
ctx.restore();
})
}
} }
</script>
</body>
</html>

底图:

canvas实现刮刮卡效果-LMLPHP

效果如下:

canvas实现刮刮卡效果-LMLPHP

05-07 15:35