原理
鼠标按住移动的时候,实现刮刮乐的效果,那就是鼠标按下的同时鼠标移动,那就清除画布。松开鼠标,鼠标移动不再清除画布了,那就得清除事件。
canvas画布
- 获取画布元素
var canvas = document.getElementById('canvas');
- 获取绘图对象getContext
var ctx = canvas.getContext('2d');
- 画线
ctx.lineWidth = 3;//线宽
ctx.strokeStyle = 'red';//线条颜色
//开始的位置 moveTo(x,y);
//结束的位置lineTo(x,y)
//执行stroke()
- 矩形ctx.rect(x,y,width,height);
ctx.rect(0,0,300,150);
ctx.fillStyle = '#ccc';//填充的颜色
ctx.fill();//执行
ctx.clearRect(e.clientX,e.clientY,20,20);//清除矩形
页面
- 页面结构
<canvas id="canvas" width="300" height="150" style="border: 1px solid #ccc;"></canvas>
<div class="prize">谢谢惠顾</div>
- 样式
.prize {
width: 300px;
height: 150px;
text-align: center;
line-height: 150px;
margin-top:-150px;
color: red;
font-size: 20px;
}
- 动画
//获取画布元素
var canvas = document.getElementById('canvas');
// 获取绘图对象
var ctx = canvas.getContext('2d');
ctx.lineWidth = 3;//线宽
ctx.strokeStyle = 'red';//线条颜色
//开始的位置 moveTo(x,y);
//结束的位置lineTo(x,y)
//执行stroke()
//矩形
ctx.rect(0,0,300,150);
ctx.fillStyle = '#ccc';//填充的颜色
ctx.fill();//执行
ctx.clearRect(e.clientX,e.clientY,20,20);
// 按下
canvas.onmousedown = function (e){
//移动
canvas.onmousemove = function (e) {
// ctx.lineTo(e.clientX,e.clientY);
// ctx.lineTo(100,100)
// ctx.stroke();
ctx.clearRect(e.clientX,e.clientY,20,20);//清除
}
}
canvas.onmouseup = function (e) {
canvas.onmousemove = null;
}
// 改变中奖信息
var arr = ['一个亿','现金500','100元话费','腾讯视频VIP月卡','谢谢惠顾'],
prize = document.querySelector('.prize'),
random = Math.floor(Math.random()*arr.length);
prize.innerText = arr[random];
完整源码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
/*----------js刮刮乐------------*/
.prize {
width: 300px;
height: 150px;
text-align: center;
line-height: 150px;
margin-top:-150px;
color: red;
font-size: 20px;
}
</style>
</head>
<body>
<!--js刮刮乐-->
<canvas id="canvas" width="300" height="150" style="border: 1px solid #ccc;"></canvas>
<div class="prize">谢谢惠顾</div>
<script>
// ------------js刮刮乐-----------
//获取画布元素
var canvas = document.getElementById('canvas');
// 获取绘图对象
var ctx = canvas.getContext('2d');
ctx.lineWidth = 3;//线宽
ctx.strokeStyle = 'red';//线条颜色
//开始的位置 moveTo(x,y);
//结束的位置lineTo(x,y)
//执行stroke()
//矩形
ctx.rect(0,0,300,150);
ctx.fillStyle = '#ccc';//填充的颜色
ctx.fill();//执行
ctx.clearRect(e.clientX,e.clientY,20,20);
// 按下
canvas.onmousedown = function (e){
//移动
canvas.onmousemove = function (e) {
// ctx.lineTo(e.clientX,e.clientY);
// ctx.lineTo(100,100)
// ctx.stroke();
ctx.clearRect(e.clientX,e.clientY,20,20);//清除
}
}
canvas.onmouseup = function (e) {
canvas.onmousemove = null;
}
// 改变中奖信息
var arr = ['一个亿','现金500','100元话费','腾讯视频VIP月卡','谢谢惠顾'],
prize = document.querySelector('.prize'),
random = Math.floor(Math.random()*arr.length);
prize.innerText = arr[random];
// ------------js刮刮乐-----------
</script>
</body>
</html>