其他分享
首页 > 其他分享> > js 连线小球代码

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>Document</title>
</head>

<body>
    <canvas id="bg" style="width: 100%;height: 100%;">
    </canvas>
</body>

</html>
<script>
    const X = 'x';
    const Y = 'y';
    const V_X = 'vx';
    const MASS = 'm';
    const V_Y = 'vy';
    const CIRCLE = 360;
    const COUNT = 300;
    const COLOR_P = '#0088ff';
    const COLOR_L = '#0088ff22';
    function initFireFly() {
        var ret = {}
        ret[X] = Math.random() * screen.width;
        ret[Y] = Math.random() * screen.height;
        ret[V_X] = (Math.random() - .5) * 5;
        ret[V_Y] = (Math.random() - .5) * 5;
        ret[MASS] = Math.random() * 2.5 + .5;
        return ret;
    };
    var list = [];
    var canvas = document.getElementById('bg');
    for (var i = 0; i < COUNT; i++) {
        list.push(initFireFly());
    }
    function run() {
        for (var i = 0; i < COUNT; i++) {
            list[i][X] += list[i][V_X];
            list[i][Y] += list[i][V_Y];
            if (list[i][X] > screen.width) {
                list[i][X] -= (list[i][X] - screen.width) * 2;
                list[i][V_X] *= -1;
            } else if (list[i][X] < 0) {
                list[i][X] += list[i][X] * -2;
                list[i][V_X] *= -1;
            }
            if (list[i][Y] > screen.height) {
                list[i][Y] -= (list[i][Y] - screen.height) * 2;
                list[i][V_Y] *= -1;
            } else if (list[i][Y] < 0) {
                list[i][Y] += list[i][Y] * -2;
                list[i][V_Y] *= -1;
            }
        }
        for (var i = 0; i < COUNT; i++) {
            var cont = canvas.getContext('2d');
            cont.beginPath();
            cont.moveTo(list[i][X], list[i][Y]);
            cont.lineWidth = 1;
            cont.strokeStyle = COLOR_P;
            cont.lineTo(list[i][X] + 1, list[i][Y] + 1);
            for (var i1 = i + 1; i1 < COUNT; i1++) {
                if (Math.sqrt(Math.pow((list[i][X] - list[i1][X]), 2) + Math.pow((list[i][Y] - list[i1][Y]), 2)) < 90) {
                    cont.strokeStyle = COLOR_L;
                    cont.lineTo(list[i1][X] + 1, list[i1][Y] + 1);
                }
            }
            cont.stroke();
        }
    }
    setInterval(function () {
        canvas.setAttribute('width', screen.width);
        canvas.setAttribute('height', screen.height);
        run();
    }, 25)
</script>

标签:const,连线,小球,screen,list,js,var,cont,Math
来源: https://blog.csdn.net/dscn15848078969/article/details/114241819