网页刮刮卡效果

网页刮刮卡效果

实现代码

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>刮刮卡效果</title>
  </head>
  <style>
    body {
      margin: 0;
    }

    #canvas {
      position: absolute;
      left: 0;
      cursor: pointer;
    }
  </style>

  <body>
    <img src="https://www.iwmyx.cn/wp-content/themes/wmyx3.0/img/logo.png" />
    <canvas id="canvas" width="1000" height="300"> </canvas>
  </body>

</html>

<script>
  function draw() {
    var canvas = document.getElementById('canvas');
    if (!canvas.getContext) return;
    var ctx = canvas.getContext('2d');
    //设置一个颜色 覆盖在这个图片上
    ctx.beginPath();
    ctx.fillStyle = "gray";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    //属性方法
    ctx.globalCompositeOperation = 'destination-out';
    //设置画笔为圆形
    ctx.lineCap = 'round';
    //设置画笔宽度
    ctx.lineWidth = 40;
    //当鼠标按下的时候
    canvas.onmousedown = function(e) {
      console.log("按下");
      //获取鼠标位置
      var x = e.clientX;
      var y = e.clientY;
      //设置鼠标位置为起始点
      ctx.moveTo(x, y);
      moves();
    }

    //当鼠标移动时候
    function moves() {
      canvas.onmousemove = function(e) {
        console.log("移动");
        var x = e.clientX;
        var y = e.clientY;
        //开始画
        ctx.lineTo(x, y);
        //描绘出路径
        ctx.stroke();
      }
    }

    //当鼠标抬起时 去除移动事件
    canvas.onmouseup = function(e) {
      console.log("抬起");
      canvas.onmousemove = "";
    }
  }
  draw();
</script>

 

© 版权声明

☆ END ☆
喜欢就点个赞吧
点赞0 分享
图片正在生成中,请稍后...