js簡單實現煙花效果


用js寫的一個簡單的煙花效果。

需要用到自己封裝的move運動函數,在別的隨筆里有封裝好的,直接調用就行。

效果圖:

 

 

js代碼:

<script type="text/javascript">
function Fire(){
    // 創建一個夜空
    this.night = document.createElement("div");
    this.setStyle(this.night,{
        width:"1000px",
        height:"500px",
        "background-color":"#000",
        border:"red solid 10px",
        position:"relative"
    })
    // 將這個夜空放到body中顯示
    document.body.appendChild(this.night)
    // 給夜空綁定單擊事件
    this.night.onclick = e=>{
        var e = e || window.event;
        var x = e.offsetX;
        var y = e.offsetY;
        this.createOneFire(x,y)
    }
}
// 創建一個小火花
Fire.prototype.createOneFire = function(x,y){
    // 創建一個小火花
    var div = document.createElement("div");
    this.setStyle(div,{
        width:"10px",
        height:"10px",
        backgroundColor:this.getColor(),
        position:"absolute",
        left:x + "px",
        bottom:0
    });
    // 將這個小火花放到夜空中
    this.night.appendChild(div)
    
    // 讓這個小火花開始運動 - 上升到指定的位置
    move(div,{top:y},()=>{
        // 將上來的這個小火花干掉
        div.parentElement.removeChild(div);
        // 創建很多小火花
        this.createMayFire(x,y)
    })
}
Fire.prototype.createMayFire = function(x,y){
    // 獲取一個隨機數
    var num = this.getRandom(100,150);
    // 定義一個數組
    // 通過循環創建多個小火花
    for(let i=0;i<num;i++){
        let div = document.createElement("div");
        // 將創建好的div放在預置的數組中
        div.setAttribute("aaa",i)
        this.setStyle(div,{
            width:"10px",
            height:"10px",
            backgroundColor:this.getColor(),
            position:"absolute",
            left:x + "px",
            top:y + "px",
            borderRadius:"50%"
        });
        this.night.appendChild(div)
        // 獲取隨機left
        var l = this.getRandom(0,this.night.clientWidth-10);
        // 獲取隨機top
        var t = this.getRandom(0,this.night.clientHeight-10);
        move(div,{left:l,top:t},()=>{
            // 刪除很多個小火花
            div.parentElement.removeChild(div)
        })
    }
}
// 獲取隨機顏色的方法
Fire.prototype.getColor = function(){
    return `rgb(${this.getRandom(0,256)},${this.getRandom(0,256)},${this.getRandom(0,256)})`
}
// 獲取隨機數的方法
Fire.prototype.getRandom = function(a,b){
    return Math.floor(Math.random()*(a-b))+b;
}
// 設置樣式的方法
Fire.prototype.setStyle = function(ele,styleObj){
    for(var attr in styleObj){
        ele["style"][attr] = styleObj[attr];
    }
}
var f = new Fire()
</script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM