JavaScript躁動的小球面向對象實現

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
* {
margin: 0;
padding: 0;
}
body,html {
height: 100%;
}
#wrap {
height: 100%;
background-color: black;
position: relative;
}
.boll {
border-radius: 50%;
position: absolute;
}

    </style>
    <script type="text/javascript">
        // 工具函數,產生[min, max)范圍內的隨機數
        // min <= x < max;
        function randFn(min, max) {
            return parseInt(Math.random() * (max-min) + min);

        }

        //  創建構造函數,由構造函數獲取小球對象
        function Boll () {
            // 小球的尺寸:隨機數
            var wh = randFn(20, 50);
            this.width = wh;
            this.height = wh;

            // 小球初始坐標點
            this.left = randFn(0, document.body.offsetWidth-wh);
            this.top = randFn(0, document.body.offsetHeight-wh);

            // 小球顏色:隨機
            this.color = 'rgba(' + randFn(0,256) + ',' + randFn(0,256) + ',' + randFn(0,256) + ',' + Math.random() + ')';

            // 小球運動速度:隨機
            this.speedX = randFn(-10, 10);
            this.speedY = randFn(-10, 10);

            // 開辟屬性,保存創建出來的DOM節點
            this.div = document.createElement('div');

        }

        // 添加繪制小球的方法
        Boll.prototype.draw = function () {
            this.div.className = 'boll';

            this.div.style.width = this.width + 'px';
            this.div.style.height = this.height + 'px';

            this.div.style.left = this.left + 'px';
            this.div.style.top = this.top + 'px';

            this.div.style.backgroundColor = this.color;

            // 把標簽拼接進文檔流
            var wrap = document.querySelector('#wrap');
            wrap.appendChild(this.div);
        }

        Boll.prototype.run = function () {
            console.log(this);
            var self = this;
            setInterval(function () {
                if (self.div.offsetLeft + self.div.offsetWidth >= document.body.offsetWidth  || self.div.offsetLeft < 0) {
                    self.speedX *= -1;
                }

                if (self.div.offsetTop + self.div.offsetHeight >= document.body.offsetHeight || self.div.offsetTop < 0) {
                    self.speedY *= -1;
                }

                self.div.style.left = self.div.offsetLeft + self.speedX + 'px';
                self.div.style.top = self.div.offsetTop + self.speedY + 'px';

            }, 10);
        }

        window.onload = function () {
            for (var i = 0; i < 100; i++) {
                var boll = new Boll();
                boll.draw();
                boll.run();
           }

        }

    </script>
</head>
<body>

    <div id="wrap">

    </div>
</body>

</html>

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容