前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >案例效果 | canvas刮刮卡抽奖

案例效果 | canvas刮刮卡抽奖

作者头像
HTML5学堂
发布2021-11-25 10:13:41
2.4K0
发布2021-11-25 10:13:41
举报
文章被收录于专栏:HTML5学堂HTML5学堂

案例效果

案例代码

HTML代码

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>刮刮卡抽奖 - 公众号:HTML5 WEB前端分享</title>
  <link rel="stylesheet" type="text/css" href="http://css.h5course.cn/reset-1.0.0.css">
    <script type="text/javascript">
    !function(N,M){function L(){var a=I.getBoundingClientRect().width;a/F>540&&(a=540*F);var d=a/10;I.style.fontSize=d+"px",D.rem=N.rem=d}var K,J=N.document,I=J.documentElement,H=J.querySelector('meta[name="viewport"]'),G=J.querySelector('meta[name="flexible"]'),F=0,E=0,D=M.flexible||(M.flexible={});if(H){console.warn("将根据已有的meta标签来设置缩放比例");var C=H.getAttribute("content").match(/initial\-scale=([\d\.]+)/);C&&(E=parseFloat(C[1]),F=parseInt(1/E))}else{if(G){var B=G.getAttribute("content");if(B){var A=B.match(/initial\-dpr=([\d\.]+)/),z=B.match(/maximum\-dpr=([\d\.]+)/);A&&(F=parseFloat(A[1]),E=parseFloat((1/F).toFixed(2))),z&&(F=parseFloat(z[1]),E=parseFloat((1/F).toFixed(2)))}}}if(!F&&!E){var y=N.navigator.userAgent,x=(!!y.match(/android/gi),!!y.match(/iphone/gi)),w=x&&!!y.match(/OS 9_3/),v=N.devicePixelRatio;F=x&&!w?v>=3&&(!F||F>=3)?3:v>=2&&(!F||F>=2)?2:1:1,E=1/F}if(I.setAttribute("data-dpr",F),!H){if(H=J.createElement("meta"),H.setAttribute("name","viewport"),H.setAttribute("content","initial-scale="+E+", maximum-scale="+E+", minimum-scale="+E+", user-scalable=no"),I.firstElementChild){I.firstElementChild.appendChild(H)}else{var u=J.createElement("div");u.appendChild(H),J.write(u.innerHTML)}}N.addEventListener("resize",function(){clearTimeout(K),K=setTimeout(L,300)},!1),N.addEventListener("pageshow",function(b){b.persisted&&(clearTimeout(K),K=setTimeout(L,300))},!1),"complete"===J.readyState?J.body.style.fontSize=12*F+"px":J.addEventListener("DOMContentLoaded",function(){J.body.style.fontSize=12*F+"px"},!1),L(),D.dpr=N.dpr=F,D.refreshRem=L,D.rem2px=function(d){var c=parseFloat(d)*this.rem;return"string"==typeof d&&d.match(/rem$/)&&(c+="px"),c},D.px2rem=function(d){var c=parseFloat(d)/this.rem;return"string"==typeof d&&d.match(/px$/)&&(c+="rem"),c}}(window,window.lib||(window.lib={}));
</script>
  <style>
    .wrap {
      padding: 10rem 0 0;
    }
    .canvas-main {
      width: 8.933333rem;
      height: 3.466666rem;
      margin: 0 auto;
      background: url(images/bg.png) center center no-repeat;
      background-size: 100%;
    }
    .wrap canvas {
      width: 8.933333rem;
      height: 3.466666rem;
    }
</style>
</head>
<body>
    <!-- 公众号:HTML5 WEB前端分享 -->
    <!-- 作者:梦幻雪冰(懂点君) -->
  <div class="wrap" id="outer">
    <div class="canvas-main">
      <canvas id="scrape-canvas"></canvas>      
    </div>
  </div>
  <script src="http://js.h5course.cn/jquery-1.11.3.min.js"></script>
  <script src="js/index.js"></script>
</body>
</html>

JavaScript代码

代码语言:javascript
复制
/**
 * 公众号:HTML5 WEB前端分享
 * 作者:梦幻雪冰(懂点君)
 */
// 显示设备的物理像素分辨率与CSS像素分辨率之比
var ratio = window.devicePixelRatio || 1,
fontem = parseInt(window.getComputedStyle(document.documentElement, null)["font-size"]),
canvas = document.getElementById('scrape-canvas'),
width = canvas.clientWidth * ratio,
height = canvas.clientHeight * ratio,
context = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;

// 绘制目标图像
context.fillStyle = '#aaa';
context.fillRect(0, 0, width, height);
context.fill();
context.font = "2rem Arial";
// 水平对齐
context.textAlign = "center";
// 垂直对齐
context.textBaseline = "middle";
context.fillStyle = "#666";
context.fillText("刮奖区", width / 2, height / 2 + 6);

// 新绘制和已经存在的canvas内容不重叠的部分的canvas内容会被保留,重叠的会透明掉
context.globalCompositeOperation = 'destination-out';

//PC端的处理
canvas.addEventListener("mousedown", handlerDownFn, false);
canvas.addEventListener("mousemove", handlerMoveFn, false);
canvas.addEventListener("mouseup", handlerUpFn, false);
//移动端的处理
canvas.addEventListener('touchstart', handlerDownFn, false);
canvas.addEventListener('touchmove', handlerMoveFn, false);
canvas.addEventListener('touchend', handlerUpFn, false);

var hasDown = false;

// 鼠标按下
function handlerDownFn(event) {
  event.preventDefault();
  hasDown = true;
}

// 鼠标移动
function handlerMoveFn(event) {
  event.preventDefault();
  
  if (hasDown) {
    if (event.changedTouches) {
      // changedTouches:涉及当前(引发)事件的触摸点的列表
      event = event.changedTouches[event.changedTouches.length - 1];
    }
    
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop,
    x = event.clientX - canvas.offsetLeft,
    y = scrollTop + event.clientY - canvas.offsetTop;

    context.beginPath();
    context.arc(x * ratio - fontem / 2, y * ratio - fontem / 2, fontem * 1, 0, Math.PI * 2, true);
    //设置globalCompositeOperation = 'destination-out',画出来是透明的
    context.fill();
  }
}

// 鼠标抬起
function handlerUpFn(event) {
  event.preventDefault();

  //得到canvas的全部数据
  var imageData = context.getImageData(0, 0, width, height),
  length = imageData.data.length,
  transparentCount = 0;
  
  for (var i = 3; i < length; i += 4) {
    // 判断alpha值是否为0,0为透明
    if (imageData.data[i] == 0) transparentCount++;
  }
  
  //当被刮开的区域等于四分之一时,则可以开始处理结果
  if (transparentCount >= (length / 4 / 4)) {
    alert('刮开啦');
  }
  
  hasDown = false;
}
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-11-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 懂点君 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档