使用了html5的新标签canvas,画布。
思想:在一个div里面写上奖项,定义一个数组,为奖池,再定义一个随机数,使奖项随机。然后整一个画布把div给盖住,然后给画布整一个鼠标按下事件,鼠标按下的时候来一个鼠标移动事件,鼠标移动的时候使画布小面积消失。鼠标抬起的时候让鼠标移动事件失效,一个简单的刮刮乐就实现了。上代码!!!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style type="text/css">
#cvs {
position: absolute;
}
#out {
width: 200px;
height: 100px;
text-align: center;
line-height: 100px;
font-size: 30px;
position: absolute;
}
</style>
<body>
<div id="out">奖项</div>
<canvas id="cvs" width="200" height="100"></canvas>
<!--画布 -->
</body>
<script type="text/javascript">
var cvs = document.getElementById("cvs");
var ctx = cvs.getContext("2d");
var arr = ["奔驰E300一辆", "300平米别墅一套", "洗衣液一袋", "谢谢惠顾", "食盐一袋"];//奖项池
var i = Math.floor(Math.random() * arr.length); //随机数据
document.getElementById("out").innerHTML = arr[i];
ctx.beginPath(); //开始绘画
ctx.fillStyle = "#eee"; //填充颜色
ctx.fillRect(0, 0, 200, 100);//矩形左上角的 x 坐标。矩形左上角的 y 坐标。矩形的宽度,以像素计。矩形的高度,以像素计。
ctx.closePath(); //关闭
cvs.onmousedown = function() {
document.onmousemove = function(e) {
var x = e.clientX - cvs.offsetLeft; //获取鼠标位置
var y = e.clientY - cvs.offsetTop;
ctx.clearRect(x, y, 20, 20);//在给定矩形内清空一个矩形
}
document.onmouseup = function() {
document.onmousedown = null;
document.onmousemove = null;
}
}
</script>
</html>
效果图: