实现的效果:主要用到画布设置图层覆盖效果globalCompositeOperation属性
实现的源代码:
- 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">恭喜你中奖iPhonediv>
- <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
-
- // 鼠标按下将变量设置为true
- canvas.onmousedown = function () {
- flag = true
- }
-
- // 鼠标抬起将变量设置为false
- canvas.onmouseup = function () {
- flag = false
- }
-
- // 鼠标移动
- canvas.onmousemove = function (e) {
- // 获取鼠标在画布中的位置
- var x = e.offsetX
- var y = e.offsetY
- // 判断鼠标是否在刮奖区域内
- if (flag) {
- // 设置图层覆盖模式
- context.globalCompositeOperation = 'destination-out'
- // 绘制一个矩形
- context.fillStyle = '#fff'
- context.fillRect(x - 10, y - 10, 20, 20)
- }
- }
- script>
- body>
- html>