基于html+js实现爆破球(面向对象写法)

使用html和js实现的一个简单小练习爆破球,大概功能主要是:

点击吐泡泡按钮,可以不停的生成大小随机的球球,且该球球在出现时会放大,放大完成会消失。该代码是面向对象的写法。详细的解释和代码步骤我都注释在下面的代码中的,请君一阅。

【注:仅作自己查看和分享学习之用】

【效果图如下】

 代码如下:

<!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>爆破球</title>
</head>

<body>
    <input type="button" value="吐泡泡">
    <script src="./qiu.js"></script>
</body>

</html>
let btn = document.getElementsByTagName("input")[0];

//圆的类
class Circle {
    constructor(w, left, top) {
        this.width = w;
        this.left = left;
        this.top = top;
        this.node = null;
        this.render();
    }
    //渲染
    render() {
        this.init();
    }
    //进行初始化
    init() {
        this.node = document.createElement("div");
        this.node.style.cssText = `
                    width:${this.width}px;
                    height:${this.width}px;
                    background-color:rgba(${getRandom(0, 255)},${getRandom(0, 255)},${getRandom(0, 255)},${getRandom(0, 10) / 10});
                    border-radius:50%;
                    position: absolute;
                    left: ${this.left}px;
                    top: ${this.top}px;
                `;
        //把该节点放到页面上去
        document.body.appendChild(this.node);
    }
}

btn.addEventListener("click", function (e) {
    let btnW = parseInt(window.getComputedStyle(btn).width);
    let btnH = parseInt(window.getComputedStyle(btn).height);

    let w = getRandom(50, 100);
    let left = getRandom(0, window.innerWidth - w - btnW);
    let top = getRandom(0, window.innerHeight - w - btnH);
    let node = new Circle(w, left, top).node;
    console.log(node);

    //通过延迟实现圆的放大
    let timer1 = setTimeout(() => {
        node.style.transform = "scale(3)";
        node.style.transition = "all linear 1000ms";
    }, 20)
    //圆放大后删除掉这个圆节点
    let timer2 = setTimeout(() => {
        node.remove();
        clearTimeout(timer1);
        clearTimeout(timer2);
    }, 800);

})

//获取随机数
function getRandom(min, max) {
    if (min > max) {
        [min, max] = [max, min];
    }
    return parseInt(Math.random() * (max - min + 1)) + min;
}

猜你喜欢

转载自blog.csdn.net/m0_71734538/article/details/129768174