<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>练习刮刮乐</title>
<style>
canvas {
position: absolute;
z-index: 2;
border: 1px solid black;
}
.text {
position: absolute;
font-size: 20px;
letter-spacing: 3px;
color: black;
height: 100px;
width: 300px;
line-height: 100px;
text-align: center;
}
</style>
</head>
<body>
<canvas id="canvas" width="300" height="100">浏览器不支持canvas</canvas>
<div class="text"></div>
</body>
<script>
window.onload = () => {
//判断移动端 or PC
function IsPC() {
var userAgentInfo = navigator.userAgent;
var Agents = ["Android", "iPhone",
"SymbianOS", "Windows Phone",
"iPad", "iPod"
];
var flag = true;
for (var v = 0; v < Agents.length; v++) {
if (userAgentInfo.indexOf(Agents[v]) > 0) {
flag = false;
break;
}
}
return flag;
}
var flag = IsPC(); //true为PC端,false为手机端
var down, move, up;
if (flag) {
down = "onmousedown";
move = "onmousemove";
up = "onmouseup";
} else {
down = "ontouchstart";
move = "ontouchmove";
up = "ontouchend";
}
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#999999"
ctx.fillRect(0, 0, 300, 100);
//鼠标按下
canvas[down] = downe => {
console.log(downe);
//鼠标开始移动
canvas[move] = movee => {
console.log(movee);
if (flag) {
ctx.clearRect(movee.clientX, movee.clientY, 15, 15);
} else {
ctx.clearRect(movee.changedTouches[0].clientX, movee.changedTouches[0].clientY, 15, 15);
}
}
}
//鼠标弹起来
canvas[up] = upe => {
console.log(upe);
//清除move事件
canvas[move] = null;
}
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
}
let random = getRandomIntInclusive(0, 5); //取0-5之间的数
console.log(random)
const prizeArry = ["周一", "周二", "周三", "周四", "周五", "周六"];
let classNode = document.querySelector(".text");
classNode.innerText = prizeArry[random];
}
</script>
</html>
这是我之前写的一个demo,步骤就是
1.创建画布,染色。
2.通过clearRect() 清空