美文网首页程序员让前端飞
js实现物体随机出现详解

js实现物体随机出现详解

作者: jia林 | 来源:发表于2018-10-03 10:26 被阅读2次

按F5或者刷新,苹果会在大盒子里随机出现,此功能可以延伸实现贪吃蛇

  • 初始化函数,里面是初始化的值
  • 创建食物函数
    1、因为是随机的,使用Math.random()
    2、随机函数的区间是0-1,所以乘以大盒子的每一单位 mapW/20
    3、利用绝对定位,给他赋值left和top
    4、left和top就是坐标(x,y)乘以自身宽高(20)
  • 最后将食物插入到大盒子里面

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        *{
            padding: 0;
            margin:0;
        }
        ul li {
            list-style: none;
        }
        #box{
            width: 500px;
            height: 500px;
            border:1px solid #ccc;
            margin:20px auto;
            position: relative;
        }
        .food{
            background:url(https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1538543361538&di=a179790c81e99f56d7675349f4565ea1&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimgad%2Fpic%2Fitem%2F37d12f2eb9389b508e646c9b8f35e5dde6116e64.jpg);
            width: 20px;
            height: 20px;
            background-size:100%;
        }
    </style>
</head>
<body>
<div id="box"></div>
</body>
<script type="text/javascript">
    var box = document.getElementById("box");
    // 初始化函数
    function init(){
        // 宽高初始值
        this.mapW = parseInt(getComputedStyle(box).width);
        this.mapH = parseInt(getComputedStyle(box).height);
        // 小盒子初始值
        this.foodW = 20;
        this.foodH = 20;
        // 坐标初始值
        this.foodX = 0;
        this.foodY = 0;
        startGame();
    }
    function startGame(){
        food()
    }
    function food(){
        // 创建小盒子
        var food = document.createElement("div");
        
        /*
            1、因为是随机的,使用Math.random()
            2、随机函数的区间是0-1,所以乘以大盒子的每一单位 mapW/20
            3、利用绝对定位,给他赋值left和top
            4、left和top就是坐标(x,y)乘以自身宽高(20)
        */
        this.foodX = Math.floor(Math.random() * (this.mapW/20));
        this.foodY = Math.floor(Math.random() * (this.mapH/20));
        food.style.position = "absolute";
        food.style.left = (this.foodX * 20) + "px";
        food.style.top = (this.foodY * 20) + "px";
        // 最后插入到大盒子里面
        box.appendChild(food).setAttribute("class","food")
    }
    init()
</script>
</html>

相关文章

网友评论

    本文标题:js实现物体随机出现详解

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