×

用CANVAS模拟一个简单的刮奖效果

作者:天空2019.06.25来源:Web前端之家浏览:7766评论:0
关键词:canvas

用CANVAS模拟一个简单的刮奖效果.

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title></title>
        <meta name="viewport" content="initial-scale=1.0, width=device-width,minimum-scale=1.0,maximum-scale=1.0, user-scalable=no" />
        <style>
            * {
                padding: 0;
                margin: 0;
            }

            .box {
                position: relative;
                height: 400px;
                width: 400px;
                margin-left: 20px;
            }

            .info {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate3d(-50%, -50%, 0);
                -webkit-transform: translate3d(-50%, -50%, 0);
            }

            .btn {
                font-size: 30px;
                color: #000;
                cursor: pointer;
            }

            .btn a {
                color: #399;
                text-decoration: none;
            }

            .canvas {
                position: absolute;
                top: 50%;
                left: 50%;
                margin-left: -200px;
                margin-top: -200px;
                z-index: 2;
            }

            .number {
                display: inline-block;
                border: 1px solid #225555;
                border-radius: 2px;
                font-size: 16px;
                margin: 10px 0 10px 50px;
                width: 60px;
                line-height: 30px;
                height: 30px;
                text-align: center;
                color: #399;
            }

            .mask {
                height: 100%;
                width: 100%;
                background: rgba(155, 155, 155, 1);
                top: 0;
                left: 0;
                z-index: 44;
                position: absolute;
            }
            .agin{
                border-radius: 4px;
                text-shadow: 1px 1px 1px #fff;
                box-shadow: 1px 1px 1px rgba(0, 0, 0, .3);
                text-align:center;
                background:#ccc;
                border:1ps solid #399;
                margin-top:20px;            
                }
            .mask a {
                display: block;
                width: 80px;
                height: 40px;
                line-height: 40px;
                font-size: 24px;
                background: #ccc;
                color: #000;
                text-decoration: none;
                text-align: center;
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate3d(-50%, -50%, 0);
                -webkit-transform: translate3d(-50%, -50%, 0);
                border-radius: 4px;
                text-shadow: 1px 1px 1px #fff;
                box-shadow: 1px 1px 1px rgba(0, 0, 0, .3);
            }
        </style>
    </head>

    <body>
        <div class='number'>200</div>
        <div class="box">
            <div class="info" id="prize">
                <p id="prompt"></p>
                <p class="btn" id="ok">
                    <a href="https://www.baidu.com/">厉害了我的哥</a>
                </p>
                <p class="btn agin" id="agin">再来一次</p>
            </div>
            <canvas id="c1" class="canvas" width='400' height="400"></canvas>
            <div class="mask">
                <a href="javascript:;">开始</a>
            </div>
        </div>
        <script>
            function Card(obj) {
                if(!obj) return;
                this.obj = obj;
                this.w = obj.width;
                this.h = obj.height;
                this.ctx = obj.getContext('2d');
                this.prize = obj.previousElementSibling;
                this.aginBtn = this.prize.querySelector('#agin');
                this.number = document.querySelector('.number');
                this.startBtn = document.querySelector('.mask a');
                this.isClear = false;
                // addEventListener 方法为了调用指向 card 
                this.handleEvent = function(event) {
                    switch(event.type) {
                        case 'touchstart':
                            this.down(event);
                            break;
                        case 'touchmove':
                            this.move(event);
                            break;
                        case 'touchend':
                            this.up(event);
                            break;
                        case 'mousedown':
                            this.down(event);
                            break;
                        case 'mousemove':

                            this.move(event);
                            break;
                        case 'mouseup':
                            this.up(event);
                            break;
                    }
                }

            }

            Card.prototype = {
                //画涂抹区
                drawGrey: function() {
                    this.prize.style.zIndex = 1;
                    this.ctx.globalCompositeOperation = "source-over";
                    this.ctx.beginPath();
                    this.ctx.fillStyle = '#aaaaaa';
                    this.ctx.fillRect(0, 0, c1.clientWidth, c1.clientHeight);
                    this.ctx.fill();
                    this.ctx.closePath();
                    this.ctx.font = "Bold 50px Arial";
                    this.ctx.textAlign = "center";
                    this.ctx.fillStyle = "#666";
                    this.ctx.lineWidth = 20; //线的宽度
                    this.ctx.lineCap = "round"; //线的两头样式为圆
                    this.ctx.lineJoin = "round"; //线的拐角样式为圆
                    this.ctx.fillText("刮一刮", c1.width / 2, c1.height / 2);
                    this.ctx.globalCompositeOperation = 'destination-out';
                },
                down: function(ev) {
                    ev.preventDefault();
                    this.isClear = true;
                },
                move: function(ev) {
                    ev.preventDefault();
                    var _this = this;
                    // 是否进入
                    var pos=this.getPos(this.obj);
                    if(!this.isClear) return;
                    if(ev.touches) {
                        var curX = ev.touches[0].pageX - pos.left;
                        var curY = ev.touches[0].pageY - pos.top;
                    } else {
                        var curX = ev.pageX - pos.left;
                        var curY = ev.pageY - pos.top;
                    }
                    var step = 16;

                    _this.ctx.save();
                    _this.ctx.beginPath();
                    _this.ctx.arc(curX, curY, step, 0, Math.PI * 2, false);
                    _this.ctx.fill();
                    _this.ctx.restore();
                },
                up: function(ev) {
                    ev.preventDefault();

                    var data = this.ctx.getImageData(0, 0, this.w, this.h).data;
                    var len = data.length;
                    var index = 0;
                    //涂抹过的区域为透明,判断alpha通道的值是否为0,计算涂抹区域
                    for(var i = 3; i < len; i += 4) {
                        if(data[i] == 0) {
                            index++;
                        }
                    }
                    //len/8一半
                    if(index >= len / 8) {
                        this.ctx.clearRect(10, 10, this.w - 20, this.h - 20);
                        this.prize.style.zIndex = 33;
                        this.index = 0;

                    }
                    this.isClear = false;
                },
                //获取积分
                getPoint: function() {
                    var _this = this;
                    _this.ajax({
                        url: '',
                        type: 'post',
                        success: function(res) {
                            if(res.error == 1000 && res.data.number) {
                                _this.number.innerHTML = res.data.number;
                            }
                        }
                    })
                },
                //              setPoint:function(num){
                //                  var _this=this;
                //                  _this.ajax({
                //                      url:'',
                //                      type:'post',
                //                      success:function(res){
                //                          if(res.error ==1000 ){
                //                              _this.number.innerHTML=num;
                //                          }
                //                      }
                //                  })
                //              },
                /*
                 * 参数 {
                 *    url:'',      地址
                 *    data:'',     请求数据
                 *    timeout:''   超时时间 默认 5000
                 *    type:''      请求方式 默认 get
                 *    success:fn   成功函数
                 *    error        失败函数      
                 * }
                 */
                ajax: function(json) {
                    json = json || {};
                    if(!json.url) return;
                    json.data = json.data || {};
                    json.timeout = json.timeout || 5000;
                    json.type = json.type.toLocaleLowerCase() || 'get';

                    var timer = null;
                    //准备 ajax 对象
                    if(window.XMLHttpRequest) {
                        var oAjax = new XMLHttpRequest();
                    } else {
                        //ie 低版本
                        var oAjax = new ActiveXObject('Microsoft.XMLHTTP');
                    }
                    //open 初始化 HTTP 请求参数   send 发送 HTTP 请求
                    switch(json.type) {
                        case 'get':
                            oAjax.open('GET', json.url + '?' + json2url(json.data), true);
                            oAjax.send();
                            break;
                        case 'post':
                            oAjax.open('POST', json.url, true);
                            oAjax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                            oAjax.send(json2url(json.data));
                            break;
                    }
                    //每次 readyState 属性改变的时候调用的事件
                    oAjax.onreadystatechange = function() {
                        //HTTP 响应已经完全接收
                        if(oAjax.readyState == 4) {
                            clearTimeout(timer);
                            //状态码 200以下为成功  304 缓存
                            if(oAjax.status >= 200 && oAjax.status < 300 || oAjax.status == 304) {
                                json.success && json.success(oAjax.responseText);
                            } else {
                                json.error && json.error(oAjax.status);
                            }
                        }
                    };
                    //网络超时
                    timer = setTimeout(function() {
                        oAjax.onreadystatechange = null;
                        alert('您的网络不给力');
                    }, json.timeout);

                },
                jude: function() {
                    var num = Number(this.number.innerHTML);
                    if(num < 100 || !num) {
                        alert('您的积分不足');
                        this.startBtn.parentNode.style.display = "block";
                        return;
                    }
                    if(num >= 100) {
                        num -= 100;
                        this.number.innerHTML = num;
                        this.startBtn.parentNode.style.display = "none";
                    }
                },
                bindEvent: function() {
                    var that = this;
                    this.aginBtn.addEventListener('click', function() {
                        that.drawGrey();
                        that.jude();
                    }, false);
                    this.startBtn.addEventListener('click', function() {
                        that.jude();
                    }, false);
                    that.obj.addEventListener('touchstart', that, false);
                    that.obj.addEventListener('touchmove', that, false);
                    that.obj.addEventListener('touchend', that, false);
                    that.obj.addEventListener('mousedown', that, false);
                    that.obj.addEventListener('mousemove', that, false);
                    that.obj.addEventListener('mouseup', that, false);
                },
                //获取到页面的位置
                getPos:function(obj){
                    var left = 0;
                    var top = 0;
                    while(obj) {
                        left += obj.offsetLeft;
                        top += obj.offsetTop;

                        obj = obj.offsetParent
                    }

                    return {
                        left: left,
                        top: top
                    };
                },
                init: function() {
                    this.drawGrey();
                //  this.getPoint();
                    this.bindEvent();
                }

            }
            window.onload = function() {
                var oc = document.getElementById('c1');
                var card = new Card(oc);
                card.init();
            }
        </script>
    </body>

</html>


您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/canvsu2834923085029385.html

网友评论文明上网理性发言 已有0人参与

发表评论: