×

JavaScript canvas应用:刮刮乐小游戏

作者:Terry2021.11.27来源:Web前端之家浏览:6873评论:0
关键词:js

分享一个使用JavaScript canvas的应用:刮刮乐小游戏,废话不多说,直接上代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>canvas实现刮刮乐 - Web前端之家www.jiangweishan.com</title>
    <style>
        .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;
        }
    </style>
</head>
<body>
    <div class="ggk">
        <span id="span">200元</span>
        <canvas id="canvas"></canvas>
    </div>

    <script>
        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
            }
        }
    </script>
</body>
</html>


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

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

发表评论: