用canvas实现一个刮刮卡效果
				
									
					
					
						|  | 
							admin 2024年10月30日 13:27
								本文热度 2335 | 
					
				 
				
先看上面的效果,这是常见的刮刮卡抽奖效果,那么前端如何使用代码实现这样的效果呢?主流方案是采用canvas来实现。
首先要实现这种效果,核心是要知道canvas的globalCompositeOperation属性,这个属性的作用是控制canvas上不同图层之间的显示效果。
这里我们需要使用到的globalCompositeOperation的destination-out属性,这个属性描述的效果是,当新图层绘制到原始图层上时候,原始图层保持在新图层不重叠的部分,仅保留现有画布内容和新形状不重叠的部分。
有了这个效果之后,我们只需要将要显示的东西放置在canvas后面就可以了,至于刮刮卡的效果,就是在 mosemove事件里面,动态绘制透明的图层到 canvas 上就好了。
代码如下:
<!DOCTYPE html>
<html>
  <head>
      <meta charset="utf-8">
      <title></title>
      <style type="text/css">
          body,html {
              width: 100%;
              height: 100%;
              display: flex;
              align-items: center;
              justify-content: center;
          }
          .box {
              user-select: none;
              position: relative;
              border: 2px solid #333;
              width: 400px;
              height: 120px;
              font-size: 50px;
              line-height: 120px;
              text-align: center;
          }
          #myCanvas {
              position: absolute;
              top: 0;
              left: 0;
          }
      </style>
  </head>
  <body>
      <div class="box">
          恭喜您,中奖了
          <canvas id="myCanvas" width="400px" height="120px"></canvas>
      </div>
  </body>
  <script type="text/javascript">
      const canvas = document.getElementById('myCanvas');
      const ctx = canvas.getContext('2d');
      ctx.fillStyle = '#ccc';
      ctx.fillRect(0, 0, 400, 120);
      ctx.globalCompositeOperation = "destination-out";
      canvas.onmousedown = function() {
          canvas.onmousemove = function(event) {
              ctx.beginPath();
              ctx.arc(event.offsetX, event.offsetY, 16, 0, 7, false);
              ctx.fill();
          }
      }
      document.body.onmouseup = function() {
          canvas.onmousemove = null;
      }
  </script>
</html>
arc(x, y, r, startAngle, endAngle, anticlockwise): 
以(x, y) 为圆心,以r 为半径,从 startAngle 弧度开始到endAngle弧度结束。
anticlosewise 是布尔值,true 表示逆时针,false 表示顺时针(默认是顺时针)。
注意:这里的度数都是弧度;0 弧度是指的 x 轴正方向。
该文章在 2024/10/30 15:13:15 编辑过