canvas实现刮刮卡效果

<style>
    * {
        margin: 0;
        padding: 0;
      }
     .wrapper {
        width: 400px;
        height: 100px;
        display: flex;
        margin: 0 auto;
        position: relative;
     }
    .text {
        position: absolute;
        left: 130px;
        top: 35px;
        z-index: -1;
      }
   </style>
  <body>
      <div class="wrapper">
        <canvas id="canvas" width="400" height="100"></canvas>
        <div class="text">恭喜您获得100w</div>
      </div>
  </body>
  <script>
        const canvas = document.getElementById('canvas')
        const ctx = canvas.getContext('2d')

        <!-- 填充的颜色 -->
        ctx.fillStyle = 'darkgray'
        <!-- 填充矩形 fillRect(起始X,起始Y,终点X,终点Y) -->
        ctx.fillRect(0, 0, 400, 100)
        ctx.fillStyle = '#fff'
        ctx.font = "20px Arial"; // 字号
        <!-- 绘制填充文字 -->
        ctx.fillText('刮刮卡', 180, 50)

        let isDraw = false
        canvas.onmousedown = function () {
            isDraw = true
        }
        canvas.onmousemove = function (e) {
            if (!isDraw) return
            <!-- 计算鼠标在canvas里的位置 -->
            const x = e.clientX - canvas.getBoundingClientRect().left + (document.body.scrollLeft || document.documentElement.scrollLeft)
            const y = e.clientY - canvas.getBoundingClientRect().top + (document.body.scrollTop || document.documentElement.scrollTop)
            <!-- 设置globalCompositeOperation -->
            ctx.globalCompositeOperation = 'destination-out'
            <!--画圆 -->
            ctx.arc(x, y, 15, 0, 2 * Math.PI)
            <!-- 填充圆形 -->
            ctx.fill()
        }
        canvas.onmouseup = function () {
            isDraw = false
        }
  </script>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容