forked from Chuyue0/javascript-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
h5_scratchCard.html
96 lines (87 loc) · 2.83 KB
/
h5_scratchCard.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />
<title>html5 canvas 简单例子学习</title>
<style type="text/css">
*{margin: 0; padding: 0; list-style: none; text-decoration: none;}
.box{width: 300px; margin: 100px auto;}
a:hover{ text-decoration: underline;}
}
</style>
</head>
<body>
<div class="box">
<div class="msg">
刮开遮挡部分看看,
<a href="javascript:void(0);" onclick="window.location.reload()">再来一次</a>
</div>
<br />
<div class="guagua">
<canvas width="320" height="160"></canvas>
</div>
</div>
</body>
<script type="text/javascript">
var bodyStyle=document.body.style;
bodyStyle.mozUserSelect="none";
bodyStyle.webkitUserSelect="none";
var img=new Image(),
canvas=document.querySelector("canvas");
canvas.style.backgroundColor="transparent";
canvas.style.position="absolute";
var imgs=['images/card01.jpg','images/card02.jpg'],
num=Math.floor(Math.random()*2);/*Math.random() * 2 生成0和2之间的随机小数,Math.floor(Math.random() * 2)生成0和2之间的随机整数*/
img.src=imgs[num];
img.addEventListener('load', function(e){
var ctx,
w=img.width,
h=img.height,
offsetX=canvas.offsetLeft,
offsetY=canvas.offsetTop,
mousedown=false;
function layer(ctx){
ctx.fillStyle='pink';
ctx.fillRect(0, 0, w, h);
}
function eventDown(e){
e.preventDefault();
mousedown=true;
}
function eventUp(e){
e.preventDefault();
mousedown=false;
}
function eventMove(e){
e.preventDefault();
if(mousedown){
if(e.changedTouches){
e=e.changedTouches[e.changedTouches.length-1];
}
var x=(e.clientX+document.body.scrollLeft || e.pageX) - offsetX || 0,
y=(e.clientY+document.body.scrollTop || e.pageY) - offsetY || 0 ;
with(ctx){
beginPath()
arc(x, y, 20, 0, Math.PI*2);
fill();
}
}
}
canvas.width=w;
canvas.height=h;
canvas.style.backgroundImage='url('+img.src+')';
ctx=canvas.getContext("2d");
ctx.fillStyle="transparent";
ctx.fillRect(0, 0, w, h);/*绘制矩形*/
layer(ctx);
ctx.globalCompositeOperation='destination-out';
canvas.addEventListener('touchstart',eventDown);
canvas.addEventListener('touchend',eventUp);
canvas.addEventListener('touchmove', eventMove);
canvas.addEventListener('mousedown',eventDown);
canvas.addEventListener('mouseup',eventUp);
canvas.addEventListener('mousemove',eventMove);
});
</script>
</html>