appendChild动画画布到2个元素

时间:2018-12-11 12:51:09

标签: javascript html canvas appendchild

我已经“继承”了先前开发人员的一些JS代码。我对JS有非常基本的了解,因此希望这是一个简单的解决方法。

JS基本上在名为“ quotes-background”的div内附加一个canvas元素。这个canvas元素中有一个时髦的小动画。

该代码非常适合页面上添加的单个canvas元素。但是我需要在同一页面的两个单独的div中添加2个动画画布。当我尝试执行此操作时,虽然我可以正确添加两个画布,但只有第二个画布(在页面底部)显示任何动画图形,而顶部的画布显示为白色...

如何修改代码以在同一页面的2个div上显示相同的移动图形?

这是我的代码:

$(function(){

        // NETWORK  BACKGROUND
        var canvas = document.createElement('canvas'),
            context = canvas.getContext('2d'),
            pool = [],
            maxPoolSize = 14,
            distanceThreshold = 120,
            lastTimestamp = 0,
            nodeConnections = [];
        canvas.className = 'netzwerkanimation';

        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        maxPoolSize = (canvas.width * canvas.height) / 10000;

        //- var ctx = canvas.getContext('2d'),
        //- ctx.fillStyle = rgb(200,201,172);
        //- ctx.fillRect(0, 0, canvas.width, canvas.height);
        //- ctx.fill();

        function Boid(x, y) {
            this.id = Boid.lastId++;
            this.position = [x, y];
            this.size = 5;
            this.color = 'rgb(0,234,40)';
            this.velocity = [1 - Math.random() * 2, 1 - Math.random() * 2];
        };

        Boid.lastId = 0;

        Boid.prototype = {
            update: function(dt) {
                for (var i = 0; i < maxPoolSize; i++) {
                    var boid = pool[i],
                        distance = this.distanceTo(boid);
                    if (distance < distanceThreshold) {
                        cohesion = []
                    }
                };

                this.position[0] += this.velocity[0] * dt;
                this.position[1] += this.velocity[1] * dt;

                if (this.position[0] > canvas.width) {
                    this.position[0] = 0;
                    // this.velocity[0] *= -1;
                }

                if (this.position[1] > canvas.height) {
                    this.position[1] = 0;
                    // this.velocity[1] *= -1;
                }

                if (this.position[0] < 0) {
                    this.position[0] = canvas.width;
                    // this.velocity[0] *= -1;
                }
                if (this.position[1] < 0) {
                    this.position[1] = canvas.height;
                    // this.velocity[1] *= -1;
                };
            },

            distanceTo: function(boid) {
                var diff = vDiff(this.position, boid.position);
                return Math.abs(vLength(diff));
            },

            isConnectedTo: function(boid) {
                return nodeConnections[boid.id] == this.id ||
                    nodeConnections[this.id] == boid.id;
            },

            connectTo: function(boid) {
                nodeConnections[this.id] = boid.id;
                nodeConnections[boid.id] = this.id;
            },

            draw: function() {
                var pos = [round(this.position[0]), round(this.position[1])],
                    connections = 0;
                context.globalAlpha = 0.5;
                for (var i = 0; i < maxPoolSize; i++) {
                    var boid = pool[i],
                        distance = this.distanceTo(boid),
                        opacity = 1 - (distance / distanceThreshold);
                    if (distance <= distanceThreshold) {
                        connections++;
                        if (!this.isConnectedTo(boid)) {
                            this.connectTo(boid);
                            context.beginPath();
                            context.moveTo(pos[0], pos[1]);
                            context.lineTo(round(boid.position[0]), round(boid.position[1]));
                            context.stroke();
                            context.strokeStyle = "rgba(200,201,172,.5)";
                        }
                    }
                };
                context.globalAlpha = 0.75;
                //- context.fillStyle = rgb(200,201,172);

                context.beginPath();
                context.arc(
                    pos[0],
                    pos[1],
                    this.size * (connections / 5),
                    0, Math.PI * 2
                );
                context.fillStyle = "rgb(200,201,172)";
                context.fill();


            }
        };

        function vDiff(a, b) {
            return [a[0] - b[0], a[1] - b[1]];
        }

        function vLength(a) {
            return Math.sqrt((a[0] * a[0]) + (a[1] * a[1]));
        }

        function round(i) {
            return 0.5 + i | 0
        }

        function draw(timestamp) {
            var dt = (timestamp - (lastTimestamp || timestamp)) / 100;
            lastTimestamp = timestamp;

            context.clearRect(0, 0, canvas.width, canvas.height);

            for (var i = 0; i < maxPoolSize; i++) {
                var boid = pool[i];
                boid.update(dt);
                boid.draw();
            }

            window.requestAnimFrame(draw);
        }

        window.requestAnimFrame = (function() {
            return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function( /* function */ callback, /* DOMElement */
                element) {
                window.setTimeout(callback, 1000 / 60);
            };
        })();

        for (var i = 0; i < maxPoolSize; i++) {
            pool.push(
                new Boid(Math.random() * canvas.width, Math.random() * canvas.height)
            );
        }
        document.getElementsByClassName("quotes-background")[0].appendChild(canvas);
 document.getElementsByClassName("quotes-background2")[0].appendChild(canvas);
        window.requestAnimFrame(draw);

    });

HTML很简单:

<div id="quotes" class="quotes">
    <div class="quotes-background">
        <!-- where the first should append-->
    </div> 
</div>

<!-- SITE CONTENT -->

<div id="quotes2" class="quotes2">
    <div class="quotes-background2">
        <!-- where the second should append-->
    </div> 
</div>

我尝试过简单地复制代码,并将所有var'canvas'更改为'canvas2',并且还尝试在末尾添加第二个append子项,例如:

document.getElementsByClassName("quotes-background")[0].appendChild(canvas);

将类名更改为quotes-background2,但这是不正确的。

0 个答案:

没有答案