canvas实现刮刮乐效果
平时浏览一些购物网站常常有一些抽奖的环节它们就会使用一种刮刮乐的形式给用户发一些优惠券或者其它的一些奖品,对此突然产生了些许兴趣于是就琢磨着该如何实现,最终还是选择了canvas来实现这个效果
思路
思路很简单,无非就是绘制一个用来刮的蒙版矩形,给画布添加鼠标移动事件,在鼠标移动时不断绘制以鼠标为圆心的圆形闭合路径,重点是图形合成globalCompositeOperation 属性使用‘destination-out’,用来抹除重叠的部分
ctx.globalCompositeOperation = ‘destination-out’
demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Title</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 90vh;
background-color: #fff;
}
#myCanvas {
background: url('C:\\Users\\Administrator\\Pictures\\Saved Pictures\\111.jpg')
center/cover;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="500px" height="300px"></canvas>
<script>
// 获取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'
// 鼠标按下事件
canvas.addEventListener('mousedown', function (e) {
canDraw = true
drawCircle(e)
})
// 鼠标弹起事件
canvas.addEventListener('mouseup', function () {
canDraw = false
})
// 鼠标移动事件
canvas.addEventListener('mousemove', function (e) {
if (canDraw) {
drawCircle(e)
}
})
// 绘制圆的方法
function drawCircle (e) {
ctx.beginPath()
ctx.arc(
e.pageX - canvas.offsetLeft,
e.pageY - canvas.offsetTop,
10,
0,
Math.PI * 2
)
ctx.fill()
ctx.closePath()
}
</script>
</body>
</html>
效果
刮前
刮后