如何利用js实现萤火虫效果

前言

前端也学习一段时间了,但是没怎么派上用场这次给大家分享一个综合案例,用原生js做萤火虫效果

首先分析萤火虫需要的步骤

1.首先先上css和body部分

<style>
        body{background:url(image/bei.jpg) ;background-size:cover }
        div{width: 100px;height: 100px;background:url(image/1.jpg);position: absolute;
            background-size:cover}
    </style>
</head>
<body>
    
</body>

因为萤火虫需要随机位置出现,和随机个数,所以在body里面我们先不用创建,在js部分中,我们先做一个随机数的函数封装,然后获取需要的dom然后创建生成div,随机生成位置随机数函数

2.1随机数函数

    function random(a,b){
        return Math.round(Math.random()*(a-b)+b)
    }

2.3获取dom和生成随机坐标

class FireFly{
        constructor(){
            this.clientW = document.documentElement.clientWidth;
            //获取body的整个可见宽度,这样可以在这个宽度里随机
            this.clientH = document.documentElement.clientHeight;
                //获取body的整个可见高度,这样可以在这个高度中随机
        }
        
        random(){
            this.x = random(0,this.clientW)-20;
            //x坐标随机0到屏幕的宽度减去自身的宽度
            this.y = random(0,this.clientH)-20;
        }

    }
    function random(a,b){
        return Math.round(Math.random()*(a-b)+b)
    }

2.3创建生成div

class FireFly{
        constructor(){
             this.clientW = document.documentElement.clientWidth;
            //获取body的整个可见宽度,这样可以在这个宽度里随机
            this.clientH = document.documentElement.clientHeight;
                //获取body的整个可见高度,这样可以在这个高度中随机
        }
        createEle(){
            var div = document.createElement("div");
            //创建一个div
            document.body.appendChild(div);
            //body中添加我们创建的div
            div.style.left = this.x + "px";
            //这个div的x坐标是我们random函数中获取的坐标
            div.style.top = this.y + "px";
            this.move(div)
        }
        random(){
            this.x = random(0,this.clientW)-20;
            //x坐标随机0到屏幕的宽度减去自身的宽度
            this.y = random(0,this.clientH)-20;
        }
       

    }

3.我们就可以先创建出这个实例

for(var i =0; i<30; i++){//假设有30只萤火虫
    var p  = new FireFly();
    p.random()//一定要先调用,先产生随机数,不然无法计算div的偏移量
    p.createEle()//创建
}

4.最后就是带入我们封装的move缓冲运动函数

class FireFly{
        constructor(){
             this.clientW = document.documentElement.clientWidth;
            //获取body的整个可见宽度,这样可以在这个宽度里随机
            this.clientH = document.documentElement.clientHeight;
                //获取body的整个可见高度,这样可以在这个高度中随机
        }
        createEle(){
            var div = document.createElement("div");
            //创建一个div
            document.body.appendChild(div);
            //body中添加我们创建的div
            div.style.left = this.x + "px";
            //这个div的x坐标是我们random函数中获取的坐标
            div.style.top = this.y + "px";
            this.move(div)
        }
        random(){
            this.x = random(0,this.clientW)-20;
            //x坐标随机0到屏幕的宽度减去自身的宽度
            this.y = random(0,this.clientH)-20;
        }
        move(ele){
            this.random();  //随机数获取坐标
            move(ele,{
                left:this.x,
                top:this.y,
            },()=>{
                this.move(ele);
            })
    }
        function random(a,b){
        return Math.round(Math.random()*(a-b)+b)
    }

整体代码如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body{background:url(image/bei.jpg) ;background-size:cover }
        div{width: 100px;height: 100px;background:url(image/1.jpg);position: absolute;
            background-size:cover}
    </style>
</head>
<body>
    
</body>
<script src="move.2.0.js"></script>
<script>
    class FireFly{
        constructor(){
            this.clientW = document.documentElement.clientWidth;
            this.clientH = document.documentElement.clientHeight;
                
        }
        createEle(){
            var div = document.createElement("div");
            document.body.appendChild(div);
            div.style.left = this.x + "px";
            div.style.top = this.y + "px";
            this.move(div)
        }
        random(){
            this.x = random(0,this.clientW)-20;
            this.y = random(0,this.clientH)-20;
        }
        move(ele){
            this.random();  
            move(ele,{
                left:this.x,
                top:this.y,
            },()=>{
                this.move(ele);
            })
        } 

    }
console.log(random(1,10));

    function random(a,b){
        return Math.round(Math.random()*(a-b)+b)
    }
for(var i =0; i<30; i++){
    var p  = new FireFly();
    p.random()
    p.createEle()
}

</script>
</html>

这一次的萤火虫案例做好了,move没有封装的人可以上我的下一篇博客分享

好的,以下是 python 实现萤火虫算法并可视化萤火虫移动过程的代码: ```python import random import math import matplotlib.pyplot as plt import numpy as np # 设置萤火虫算法的参数 num_fireflies = 20 # 萤火虫数量 num_iter = 10 # 迭代次数 alpha = 0.2 # 吸引因子 beta = 1 # 感应因子 gamma = 1 # 收缩因子 delta = 0.97 # 衰减因子 xmin, xmax, ymin, ymax = -5, 5, -5, 5 # 随机生成萤火虫的范围 def init_fireflies(num_fireflies): """ 随机初始化萤火虫的位置和亮度(即适应度值) """ fireflies = [] for i in range(num_fireflies): x = xmin + (xmax - xmin) * random.random() y = ymin + (ymax - ymin) * random.random() intensity = -1 # 初始亮度为-1 fireflies.append([x, y, intensity]) return fireflies def distance(f1, f2): """ 计算两个萤火虫之间的距离 """ return math.sqrt((f1[0] - f2[0]) ** 2 + (f1[1] - f2[1]) ** 2) def brightness(f): """ 计算萤火虫的亮度(即适应度值) """ return math.exp(-distance(f, [0, 0]) ** 2) def move(f, brightest): """ 根据萤火虫的亮度和距离,更新萤火虫的位置 """ r = distance(f, brightest) theta = random.uniform(-math.pi, math.pi) x = f[0] + beta * math.exp(-gamma * r ** 2) * math.cos(theta) + alpha * (random.random() - 0.5) y = f[1] + beta * math.exp(-gamma * r ** 2) * math.sin(theta) + alpha * (random.random() - 0.5) x = max(xmin, min(x, xmax)) y = max(ymin, min(y, ymax)) intensity = brightness([x, y]) return [x, y, intensity] def find_brightest(fireflies): """ 找到亮度最大的萤火虫 """ brightest = None for f in fireflies: if brightest is None or f[2] > brightest[2]: brightest = f return brightest def main(): # 初始化萤火虫 fireflies = init_fireflies(num_fireflies) # 记录每次迭代的最优解 best_scores = [] # 迭代 for i in range(num_iter): # 找到亮度最大的萤火虫 brightest = find_brightest(fireflies) # 更新萤火虫的位置 for j in range(num_fireflies): fireflies[j] = move(fireflies[j], brightest) # 衰减吸引因子 alpha *= delta # 记录最优解 best_scores.append(brightest[2]) # 可视化萤火虫移动过程 plt.clf() for f in fireflies: plt.scatter(f[0], f[1], c='r') plt.scatter(brightest[0], brightest[1], c='b') plt.title('Iteration %d' % (i + 1)) plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) plt.pause(0.1) # 打印最优解 print('Best solution: (%f, %f)' % (brightest[0], brightest[1])) # 绘制最优解的亮度曲线 plt.clf() plt.plot(best_scores) plt.title('Brightness of the brightest firefly') plt.xlabel('Iteration') plt.ylabel('Brightness') plt.show() if __name__ == '__main__': main() ``` 运行代码后,会弹出一个窗口,不停地显示萤火虫的移动过程。在每次迭代结束后,会打印当前最优解的位置,以及最优解的亮度曲线。可以根据需要修改萤火虫算法的参数和随机生成萤火虫的范围。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值