今日无事,写一个刮刮乐用于收割亲弟弟零花钱
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Title</title>
<style>
body {
height: 100vh;
background-color: #fff;
}
.textDiv {
position: absolute;
width: 500px;
height: 300px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 40px;
color: #333;
background-color: #ddc6c6;
display: flex;
justify-content: center;
align-items: center;
}
canvas {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="textDiv"></div>
<canvas id="myCanvas" width="500px" height="300px"></canvas>
<script>
// 奖励及其对应概率
const rewards = [
{ amount: "谢谢惠顾", probability: 0.5 },
{ amount: "1元", probability: 0.2 },
{ amount: "2元", probability: 0.1 },
{ amount: "5元", probability: 0.1 },
{ amount: "10元", probability: 0.06 },
{ amount: "50元", probability: 0.04 },
];
const cumulativeProbabilities = [];
let sum = 0;
rewards.forEach((reward, index) => {
sum += reward.probability;
cumulativeProbabilities[index] = sum;
});
// 随机获取奖励的方法
const getRandomReward = () => {
const randomNum = Math.random();
for (let i = 0; i < cumulativeProbabilities.length; i++) {
if (randomNum <= cumulativeProbabilities[i]) {
return rewards[i].amount;
}
}
};
// 更新文字显示的方法
const updateText = (amount) => {
const textDiv = document.querySelector(".textDiv");
textDiv.textContent = amount;
};
const reward = getRandomReward();
updateText(reward);
const drawCanvas = () => {
// 获取canvas对象
const canvas = document.getElementById("myCanvas");
// 获取上下文对象
const ctx = canvas.getContext("2d");
// 判断鼠标是否处于按压状态
let canDraw = false;
// 给画布绘制刮层蒙版
ctx.fillStyle = "#9c9fb3";
ctx.fillRect(0, 0, 500, 300);
// 绘制“刮一刮”字样
ctx.font = "40px Arial";
ctx.fillStyle = "#333";
ctx.fillText("刮一刮", 180, 150);
// 重点:利用 globalCompositeOperation 属性来改变绘制图形重叠的合成样式,以下‘destination-out’仅仅保留老图像与新图像没有重叠的部分
ctx.globalCompositeOperation = "destination-out";
// 绘制圆的方法
const drawCircle = (e) => {
ctx.beginPath();
var rect = canvas.getBoundingClientRect();
var x = event.clientX - rect.left;
var y = event.clientY - rect.top;
ctx.arc(x, y, 40, 0, Math.PI * 2);
ctx.fill();
ctx.closePath();
};
// 鼠标按下事件
canvas.addEventListener("mousedown", function (e) {
canDraw = true;
drawCircle(e);
});
// 鼠标弹起事件
canvas.addEventListener("mouseup", function () {
canDraw = false;
});
// 鼠标移动事件
canvas.addEventListener("mousemove", function (e) {
if (canDraw) {
drawCircle(e);
}
});
};
drawCanvas();
</script>
</body>
</html>