效果展示:
代码如下:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="./index.js"></script>
<style>
#canvas {
position: absolute;
margin-top: 1px;
margin-left: 1px;
}
.prize {
border: 1px solid black;
width: 300px;
height: 150px;
line-height: 150px;
text-align: center;
color: red;
font-size: 30px;
}
</style>
</head>
<body>
<canvas id="canvas" width="300" height="150"></canvas>
<div class="prize"></div>
</body>
</html>
index.js
window.onload = function () {
//选择器封装
function $(name) {
return document.querySelector(name);
}
//获取画布元素
var canvas = $("#canvas");
//获取绘图对象
var ctx = canvas.getContext("2d");
ctx.lineWidth = 3; //线宽
//矩形
ctx.rect(0, 0, 300, 150); //ctx.react(左上角x,左上角y,width,height);
ctx.fillStyle = "#ccc"; //填充颜色
ctx.fill(); //执行填充
// ctx.clearRect(50, 50, 50, 50); //清除区域
//鼠标按下事件
canvas.onmousedown = function (e) {
canvas.onmousemove = function (e) {
ctx.clearRect(e.clientX, e.clientY, 15, 15);
};
};
//鼠标松开事件
canvas.onmouseup = function (e) {
canvas.onmousemove = null;
};
//中奖信息
var arr = [
"一等奖 一个亿",
"二等奖 海景别墅",
"三等奖 一万",
"100元话费",
"谢谢惠顾",
];
var prize = $(".prize");
//随机数据
var i = Math.floor(Math.random() * arr.length);
prize.innerHTML = arr[i];
};