canvas实现简单的刮刮乐功能

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>

效果

刮前
在这里插入图片描述
刮后
在这里插入图片描述

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值