H5刮刮卡效果

36次阅读

共计 1479 个字符,预计需要花费 4 分钟才能阅读完成。

效果图:

核心就是使用 ctx.globalCompositeOperation = ‘destination-out’;

全部代码:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
    .ggk{
        width:200px;
        height: 100px;
        border:1px solid #ccc;
        margin:0 auto;
        color:red;
        position: relative;
    }
    .ggk span{
        position: absolute;
        width:100%;
        height: 100%;
        text-align: center;
        font-size:50px;
        line-height: 100px;
    }
    canvas{
        position: absolute;
        left:0;
        top:0;
    }
    </style>
</head>
<body>

<div class='ggk'>
    <span id='span'>200 元 </span>
    <canvas id='canvas'></canvas>
</div>

<script type="text/javascript">
var canvas = document.getElementById("canvas");
init();

function init(){
    canvas.width = 200;
    canvas.height = 100;
    var ctx = canvas.getContext("2d");
    productResult();
    drawCover(ctx);
    drawStroke(ctx);

}
// 往 span 内填充内容
function productResult(){var span = document.getElementById("span");
    var arr = ['100 元','100 元','200 元','300 元','谢谢','谢谢','谢谢','谢谢','谢谢','谢谢'];
    var text = arr[randomInt(0,arr.length-1)];
    span.innerHTML = text;
}    
// 产生随机值
function randomInt(from,to){return parseInt( Math.random()*(to-from+1)+from );
}
// 绘制覆盖层 ==》灰色
function drawCover(ctx){ctx.save();
    ctx.fillStyle = "rgb(100,100,100)";
    ctx.fillRect(0,0,200,100);
    ctx.restore();}
function  drawStroke(ctx){canvas.onmousedown = function(e){

        var downX = e.offsetX;
        var downY = e.offsetY;
        ctx.beginPath();
        ctx.globalCompositeOperation = 'destination-out';
        ctx.lineWidth = 10;
        ctx.moveTo(downX,downY);

        canvas.onmousemove = function(e){
            var x = e.offsetX;
            var y = e.offsetY;
            ctx.lineTo(x,y);
            ctx.stroke();}

    }
    canvas.onmouseup = function(){canvas.onmousemove = null;}

}

</script>
</body>
</html>

每日分享效果附带视频:https://www.3mooc.com/front/c…

正文完
 0