实现的效果:主要用到画布设置图层覆盖效果globalCompositeOperation属性
实现的源代码:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>刮刮卡抽奖效果</title><style>* {padding: 0;margin: 0;}#app {width: 600px;height: 400px;line-height: 400px;text-align: center;}#myCanvas {position: fixed;top: 0;left: 0;z-index: 9;}</style></head><body><div id="app">恭喜你中奖iPhone</div><canvas id="myCanvas" width="600" height="400"></canvas><script>var canvas = document.getElementById('myCanvas')var context = canvas.getContext('2d')// 画一个刮奖图层context.fillStyle = '#aaa'context.fillRect(0, 0, canvas.width, canvas.height)context.font = '30px Arial'context.fillStyle = 'red'context.fillText('刮开图层抽奖', 230, 200)// 设置一个变量let flag = false// 鼠标按下将变量设置为truecanvas.onmousedown = function () {flag = true}// 鼠标抬起将变量设置为falsecanvas.onmouseup = function () {flag = false}// 鼠标移动canvas.onmousemove = function (e) {// 获取鼠标在画布中的位置var x = e.offsetXvar y = e.offsetY// 判断鼠标是否在刮奖区域内if (flag) {// 设置图层覆盖模式context.globalCompositeOperation = 'destination-out'// 绘制一个矩形context.fillStyle = '#fff'context.fillRect(x - 10, y - 10, 20, 20)}}</script></body>
</html>