canvas刮奖游戏

<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<title>canvas刮奖游戏</title>
	<style>
		* {
			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;
		}
	</style>
</head>

<body>
	<canvas id="canvas" width="300" height="150"></canvas>
	<div class="prize">谢谢惠顾</div>

	<script>
		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 i = Math.floor(Math.random() * arr.length);  //随机数 parseInt
		console.log(i);
		document.querySelector(".prize").innerText = arr[i];   //0-5
	</script>
</body>

</html>

  

posted @ 2021-02-01 11:49  lanyan  阅读(85)  评论(0编辑  收藏  举报