H5刮刮卡效果

2019-10-08  本文已影响0人  终身成长人格

又到了每日分享时间了,这次分享为:H5刮刮卡效果。
效果图:


image.png

核心就是使用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/couinfo/998

上一篇下一篇

猜你喜欢

热点阅读