JS 第三方工具封装经典案例(刮刮乐)

css

*{
    margin: 0;
    padding: 0;
}
.prize {
    position: absolute;
    width: 300px;
    height: 150px;
    text-align: center;
    line-height: 150px;
    font-size: 30px;
    color: red;
}
#canvas{
    border: 1px solid #000;	
    position: absolute;
    z-index: 2;
}

html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>canvas刮奖游戏</title>
		<link rel="stylesheet" href="index.css">
  		<script src="index.js"></script>
	</head>
	<body>
		<canvas id="canvas" width="300" height="150"></canvas>
		<div class="prize">谢谢惠顾</div>
	</body>

</html>

js

window.onload = function(){
	var flag = false; //是否在拖动中
	var canvas = document.getElementById("canvas");
	var ctx = canvas.getContext("2d");  //绘制图形

	//画一个矩形
	ctx.beginPath(); //开始路径
	ctx.rect(0,0,300,150);  //绘制矩形    fillRect 实心   strokeRect空心 ,只有边框
	ctx.fillStyle='#c0c0c0';//填充颜色
	ctx.fill();   //填充
	ctx.closePath(); //关闭路径
	
	//按下事件
	canvas.onmousedown = function(event){    //event对象    事件的状态  e.target
		flag = true;
	};
		//移动事件
		canvas.onmousemove = function(event){
			if(!flag) {
				return;
			}
			var x = event.clientX;    //与X轴的距离
			var y = event.clientY;   //与Y轴的距离
			//清除绘制
			ctx.clearRect(x,y,20,20);
		}
	//松开事件
	canvas.onmouseup= function(event){    //event对象    事件的状态  e.target
		flag = false;
	};

	//中奖信息
	var arr = ['一个亿','海景别墅','一等奖','二等奖','100元话费','10G流量','谢谢惠顾'];
	var prize = document.querySelector(".prize");
	var i = Math.floor(Math.random()*arr.length);  //随机数 parseInt
	console.log(i);
	prize.innerText = arr[i];   //0-5

}

你可能感兴趣的:(前端)