< 返回技术文档列表

怎么用JavaScript canvas实现刮刮效果

发布时间:2021-11-07 02:05:32⊙投诉举报

本篇内容主要讲解“怎么用JavaScript canvas实现刮刮效果”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么用JavaScript canvas实现刮刮效果”吧!

具体内容如下

HTML代码:

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

css代码:

.ggk {
            width: 200px;
            height: 100px;
            border: 1px solid #000;
            margin: 20px 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;
        }

js代码:

var canvas = document.getElementById("canvas")
        init()
        function init() {
            canvas.width = 200;
            canvas.height = 100;
            var ctx = canvas.getContext("2d")
            //  覆盖一层灰色
            ctx.save();
            ctx.fillStyle = 'rgb(100,100,100)'
            ctx.fillRect(0, 0, 200, 100)
            draw(ctx)
            pro()
        }
 
        //  随机内容
        function pro() {
            var span = document.getElementById("span")
            var arr = ["100元", '谢谢惠顾', '200元', '谢谢惠顾', '谢谢惠顾', '谢谢惠顾', '500万', '谢谢惠顾']
            var num = Math.floor(Math.random() * (arr.length - 1))
            var text = arr[num]
            span.innerHTML = text
        }
 
        function draw(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.clearRect(x,y,20,20)
                    ctx.stroke()
 
                }
            }
            // 鼠标弹起事件
            canvas.onmouseup = function(){
                canvas.onmousemove = null
            }
        }

到此,相信大家对“怎么用JavaScript canvas实现刮刮效果”有了更深的了解,不妨来实际操作一番吧!这里是血鸟云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!


/template/Home/Zkeys/PC/Static