美文网首页
用H5实现刮奖样式

用H5实现刮奖样式

作者: 程序猿某人_ | 来源:发表于2017-01-10 17:19 被阅读0次

    效果如下:

    ![4C2Y`_$MP(PDU4_X[FQE@K.png

    话不多说直接上代码:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
       <div class="msg">
          <button onclick="window.location.reload()">再试一次</button>
       </div>
       <canvas class="canvas"></canvas>
    </body>
    <script type="text/javascript">
        var bodystyle = document.body.style;  
        bodystyle.mozUserSelect = "none";     
        bodystyle.webkitUserSelect = "none";
        var img = new Image();
        var canvas = document.querySelector('canvas');
        canvas.style.backgrountColor = "transparent";
        canvas.style.position = 'absolute';
        var imgs = ['http://labfile.oss.aliyuncs.com/courses/133/p_0.jpg','http://labfile.oss.aliyuncs.com/courses/133/p_1.jpg'];
        var num = Math.floor(Math.random()*2);
        img.src = imgs[num];
        img.addEventListener('load',function(e){
            var ctx;
            var w = img.width,
                h = img.height;        
            var offsetX = canvas.offsetLeft,
                offsetY = canvas.offsetTop;
            var mouseDown = false;
    
            function layer(ctx){
                ctx.fillStyle = "gray";
                ctx.fillRect(0,0,w,h)
            }
            function eventDown(e){
                e.preventDefault();
                mouseDown = true;
            }
            function eventUp(e){
                e.preventDefault();
                mouseDown = false;
            }
            function eventMove(e){
                e.preventDefault();
                if(mouseDown){      
                    var x =  e.pageX -offsetX;
                    var y =  e.pageY - offsetY;
                    with(ctx) {
                        beginPath();
                        arc(x,y,10,0,Math.PI *2);
                        fill();
                    }
                }
            }
    
            canvas.width = w;
            canvas.height = h;
            canvas.style.backgroundImage = 'url(' + img.src + ')';
            ctx = canvas.getContext('2d');
            ctx.fillStyle = 'transparent';
            ctx.fillRect(0,0,w,h);
            layer(ctx);
            ctx.globalCompositeOperation = 'destination-out';
            canvas.addEventListener('touchstart',eventDown);
            canvas.addEventListener('touchend',eventUp);
            canvas.addEventListener('touchmove',eventMove);
            canvas.addEventListener('mousedown',eventDown);
            canvas.addEventListener('mouseup',eventUp);
            canvas.addEventListener('mousemove',eventMove);
        },false)
    
    </script>
    </html>
    

    相关文章

      网友评论

          本文标题:用H5实现刮奖样式

          本文链接:https://www.haomeiwen.com/subject/kqtlbttx.html