Home Web Front-end JS Tutorial js to achieve scratch card effect on PC and mobile terminals

js to achieve scratch card effect on PC and mobile terminals

Feb 15, 2017 pm 05:58 PM

This article mainly introduces js to realize the scratch card effect on PC and mobile terminals in detail. It has a certain reference value. Interested friends can refer to it.

The examples in this article are shared with everyone. The specific code for the js scratch card effect is for your reference. The specific content is as follows

Effect picture:

js to achieve scratch card effect on PC and mobile terminals

Specific code:

<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>小月博客刮刮卡案例分享</title>
    <script src="http://cdn.bootcss.com/jquery/2.1.4/jquery.min.js"></script>
    <style type="text/css">
      * {
        padding: 0;
        margin: 0;
        list-style: none;
      }

      body {
        background: #E34830;
        position: relative;
      }

      .banner1 {
        display: block;
        width: 100%;
        /*height: auto;*/
        overflow: hidden;
      }

      .ggl {
        position: relative;
        width: 85.6%;
        height: 90px;
        margin: -5px auto;
        background: url(img/ggl.png) no-repeat center center;
        background-size: 100% 100%;
        border: 1px solid blue;
      }

      .canvas {
        position: absolute;
        top: 2px;
        left: 2.5%;
        width: 95%;
        height: 82px;
        line-height: 82px;
        text-align: center;
        z-index: 2;
        border: 1px solid black;
      }

      .info {
        position: absolute;
        top: 2px;
        left: 2.5%;
        width: 95%;
        height: 82px;
        text-align: center;
      }

      .info span {
        display: block;
        font-size: 18px;
      }

      #prompt {
        line-height: 40px;
      }

      .btn {
        position: relative;
        width: 50%;
        height: 35px;
        line-height: 35px;
        background: #df412b;
        color: #fff;
        border-radius: 5px;
        margin: 0 auto;
        z-index: 1;
      }

      .guize {
        display: block;
        width: 85.6%;
        height: auto;
        margin: 5% auto 10% auto;
        border-radius: 5px;
        border: 1px solid black;
      }

      .num {
        width: 90%;
        margin: 0 auto;
        height: 30px;
        line-height: 30px;
        text-align: center;
        font-size: 14px;
        margin-top: 5%;
        border: 1px solid black;
      }

      #ok,
      #no {
        display: none;
      }

      .pop {
        position: fixed;
        left: 0;
        top: 0;
        z-index: 3;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.6);
        display: none;
      }

      .pop img {
        width: 100%;
        height: auto;
        overflow: hidden;
        margin: 15% auto;
      }
    </style>
    <script>
      //控制刮卡次数
      var t = 0;
      //初始化所有数据并且随机产生奖品
      var initialize = function() {
        //剩余刮卡次数
        $(&#39;.num1&#39;).html(4 - t);
        //随机数
        function getRandomNum(lbound, ubound) {
          return (Math.floor(Math.random() * (ubound - lbound)) + lbound);
        }
        var r = getRandomNum(1, 100);
        var btn = document.getElementsByClassName("btn");
        for (var i = 0; i < btn.length; i++) {
          btn[i].style.zIndex = &#39;1&#39;;
        }
        document.getElementById("no").style.display = "none";
        document.getElementById("ok").style.display = "none";

        //初始化涂抹面积
        isOk = 0;

        if (r < t * 33) {
          document.getElementById("prompt").innerHTML = "恭喜您,中奖了!"
          var ok = document.getElementById("ok");
          ok.style.display = "block";
          //点击领取奖品
          ok.onclick = function() {
            window.location.href = "prize.html"
          };
        } else {
          document.getElementById("prompt").innerHTML = "很遗憾,未中奖!"
          document.getElementById("no").style.display = "block";
        }
      };

      var c1; //画布
      var ctx; //画笔
      var ismousedown; //标志用户是否按下鼠标或开始触摸
      var isOk = 0; //标志用户是否已经刮开了一半以上
      var fontem = parseInt(window.getComputedStyle(document.documentElement, null)["font-size"]); //这是为了不同分辨率上配合@media自动调节刮的宽度

      /* 页面加载后开始初始化画布 */
      window.onload = function() {
        initialize();
        c1 = document.getElementById("c1");

        //这里很关键,canvas自带两个属性width、height,我理解为画布的分辨率,跟style中的width、height意义不同。
        //最好设置成跟画布在页面中的实际大小一样
        //不然canvas中的坐标跟鼠标的坐标无法匹配
        c1.width = c1.clientWidth;
        c1.height = c1.clientHeight;
        ctx = c1.getContext("2d");

        //PC端的处理
        c1.addEventListener("mousemove", eventMove, false);
        c1.addEventListener("mousedown", eventDown, false);
        c1.addEventListener("mouseup", eventUp, false);

        //移动端的处理
        c1.addEventListener(&#39;touchstart&#39;, eventDown, false);
        c1.addEventListener(&#39;touchend&#39;, eventUp, false);
        c1.addEventListener(&#39;touchmove&#39;, eventMove, false);

        //初始化
        initCanvas();
      }

      //初始化画布,画灰色的矩形铺满
      function initCanvas() {
        //网上的做法是给canvas设置一张背景图片,我这里的做法是直接在canvas下面另外放了个p。
        //c1.style.backgroundImage="url(中奖图片.jpg)";
        ctx.globalCompositeOperation = "source-over";
        ctx.fillStyle = &#39;#aaaaaa&#39;;
        ctx.fillRect(0, 0, c1.clientWidth, c1.clientHeight);
        ctx.fill();

        ctx.font = "Bold 30px Arial";
        ctx.textAlign = "center";
        ctx.fillStyle = "#999999";
        ctx.fillText("刮一刮", c1.width / 2, 50);

        //把这个属性设为这个就可以做出圆形橡皮擦的效果
        //有些老的手机自带浏览器不支持destination-out,下面的代码中有修复的方法
        ctx.globalCompositeOperation = &#39;destination-out&#39;;
      }

      //鼠标按下 和 触摸开始
      function eventDown(e) {
        e.preventDefault();
        ismousedown = true;
      }

      //鼠标抬起 和 触摸结束
      function eventUp(e) {
        e.preventDefault();

        //得到canvas的全部数据
        var a = ctx.getImageData(0, 0, c1.width, c1.height);
        var j = 0;
        for (var i = 3; i < a.data.length; i += 4) {
          if (a.data[i] == 0) j++;
        }

        //当被刮开的区域等于一半时,则可以开始处理结果
        if (j >= a.data.length / 8) {
          isOk = 1;
        }
        ismousedown = false;
      }

      //鼠标移动 和 触摸移动
      function eventMove(e) {
        e.preventDefault();
        if (ismousedown) {
          if (e.changedTouches) {
            e = e.changedTouches[e.changedTouches.length - 1];
          }
          var topY = document.getElementById("top").offsetTop;
          var oX = c1.offsetLeft,
            oY = c1.offsetTop + topY;

          var x = (e.clientX + document.body.scrollLeft || e.pageX) - oX || 0,
            y = (e.clientY + document.body.scrollTop || e.pageY) - oY || 0;

          //画360度的弧线,就是一个圆,因为设置了ctx.globalCompositeOperation = &#39;destination-out&#39;;
          //画出来是透明的
          ctx.beginPath();
          ctx.arc(x, y, fontem * 1.2, 0, Math.PI * 2, true);

          //下面3行代码是为了修复部分手机浏览器不支持destination-out
          //我也不是很清楚这样做的原理是什么
          c1.style.display = &#39;none&#39;;
          c1.offsetHeight;
          c1.style.display = &#39;inherit&#39;;

          ctx.fill();
        }

        if (isOk) {
          var btn = document.getElementsByClassName("btn");
          for (var i = 0; i < btn.length; i++) {
            btn[i].style.zIndex = &#39;3&#39;;
          }
          document.getElementsByClassName("btn")[0].style.zIndex = "3";
        }
      }

      //没有中奖再来一次
      $("#no").click(function() {
        if (t > 3) {
          //因该弹出遮罩层提示您的次数已经用完了
          $(&#39;.pop1&#39;).show();
          $(&#39;.pop1 img&#39;).click(function() {
            $(&#39;.pop1&#39;).hide();
          })
        } else {
          t++;
          //初始化按钮
          document.getElementById("no").style.display = "none";
          document.getElementById("ok").style.display = "none";
          window.onload();
          initCanvas();

        }
      });
    </script>
  </head>

  <body>
    <img  class="banner1 lazy"  src="/static/imghw/default1.png"  data-src="img/banner1.png"    / alt="js to achieve scratch card effect on PC and mobile terminals" >
    <p class="ggl" id="top">
      <p class="info" id="prize">
        <span id="prompt"></span>
        <span class="btn" id="ok">领取奖品</span>
        <span class="btn" id="no">再来一次</span>
      </p>
      <canvas id="c1" class="canvas"></canvas>
    </p>
    <p class="num">
      您还有<span class="num1"></span>次刮卡机会
    </p>
    <img  class="guize lazy"  src="/static/imghw/default1.png"  data-src="img/guize.png"    / alt="js to achieve scratch card effect on PC and mobile terminals" >

    <!-- 遮罩层1抽奖次数已经用完-->
    <p class="pop pop1">
      <img  src="/static/imghw/default1.png"  data-src="img/pop1.png"  class="lazy"   / alt="js to achieve scratch card effect on PC and mobile terminals" >
    </p>
    <p class="pop pop2">
      <img  src="/static/imghw/default1.png"  data-src="img/pop2.png"  class="lazy"   id="pop2" / alt="js to achieve scratch card effect on PC and mobile terminals" >
    </p>
  </body>

</html>
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.

Please pay attention to the PHP Chinese website for more articles related to js realizing scratch card effect on PC and mobile terminals!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles