<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<title>演示:使用HTML5实现刮刮卡效果</title>
<style type="text/css">
.demo {
width: 320px;
margin: 10px auto 20px auto;
min-height: 300px;
position: relative;
}
.msg {
text-align: center;
height: 32px;
line-height: 32px;
font-weight: bold;
margin-top: 50px;
}
#canvas {
position: relative;
}
.background {
position: absolute;
width: 100%;
text-align: center;
line-height: 160px;
font-size: 24px;
font-weight: bold;
}
</style>
</head>
<body>
<div id="main">
<div class="msg">
刮开灰色部分看看,<a href="javascript:void(0)" onClick="window.location.reload()">再来一次</a>
</div>
<div class="demo">
<div class="background">恭喜中奖</div>
<canvas id="canvas"></canvas>
</div>
</div>
<script type="text/javascript">
var canvas = document.getElementById("canvas")
var rect = canvas.getBoundingClientRect()
var canvas_width = 320
var canvas_height = 160
window.onload = function() {
var mousedown = false;
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[0]
var x = e.clientX - rect.left
var y = e.clientY - rect.top
ctx.beginPath()
ctx.arc(x, y, 20, 0, Math.PI * 2)
ctx.fill();
}
handleFilledPercentage(getFilledPercentage());
}
function getFilledPercentage() {
// data是个数组,存储着指定区域每个像素点的信息,数组中4个元素表示一个像素点的rgba值
var pixels = ctx.getImageData(0, 0, canvas_width, canvas_height).data
var cleaned = 0 // 已清除的像素
for (var pixel_index = 0; pixel_index < pixels.length; pixel_index += 4)
// 严格上来说,判断像素点是否透明需要判断该像素点的a值是否等于0,
// 为了提高计算效率,这儿设置当a值小于128,也就是半透明状态时就可以了
if (pixels[pixel_index + 3] < 128)
++cleaned
return cleaned * 4 / pixels.length
}
function handleFilledPercentage(percentage) {
if (percentage > 0.5)
ctx.clearRect(0, 0, canvas_width, canvas_height);
}
// 动态设置canvas元素大小
canvas.width = canvas_width;
canvas.height = canvas_height;
var ctx = canvas.getContext("2d")
ctx.fillStyle = "grey";
ctx.fillRect(0, 0, canvas_width, canvas_height);
ctx.fillStyle = "green";
ctx.font = "48px sans-serif"
ctx.textAlign = "center" // 文字居中
ctx.fillText("刮开涂层", canvas_width / 2, 95)
ctx.globalCompositeOperation = "destination-out";
ctx.setLineDash([20, 5]); // [实线长度, 间隙长度]
ctx.lineDashOffset = 0;
ctx.strokeRect(20, 20, 280, 120);
// 移动端(触控事件)
canvas.addEventListener("touchstart", eventDown);
canvas.addEventListener("touchend", eventUp);
canvas.addEventListener("touchmove", eventMove);
// PC端(鼠标事件)
canvas.addEventListener("mousedown", eventDown);
canvas.addEventListener("mouseup", eventUp);
canvas.addEventListener("mousemove", eventMove);
}
</script>
</body>
</html>
网友评论