有没有更有效的方法来使用 javascript 中的 p5.js 将 p5.graphics 像素数组设置为等于另一个像素数组?

Is there a more efficient way to set a p5.graphics pixel array equal to another using p5.js in javascript?

我目前正在使用 p5.js 库开发爬坡遗传算法程序。

该程序使用遗传算法格式重新创建您想要的任何图像。它的工作原理类似于我在 youtube 上找到的视频 this program

我有一个基因 class,除其他外,它有一个名为 'graphic' 的属性,一旦基因被创建,它就被设置为一个新的 p5.graphic 对象。

还有一个种群 class,它有一个名为 'genes' 的属性,它是一个包含 10 个基因对象的数组。 Population class 的方法 getHealthiest() returns 基因数组中的基因图形看起来最像目标图像。此外,在 Population class 中,有一个 evolve() 方法。

这是我的问题所在。在 evolve() 方法中,我想 1. 确定最健康的基因和 2. 清空除最健康基因之外的基因数组,并用最健康基因的其他 9 个基因重新填充它。为此,我需要将新基因的图形属性设置为与最健康的基因相同。

    this.evolve = function() {
        var healthiestGene = this.getHealthiest(); //sets a variable equal to the healthiest gene
        this.genes = []; //clearing out the genes array of the population
        for (var i=0; i < this.populationSize; i++) {
            this.genes[i] = new Gene(this.target); //creating a new Gene object

            //This is the problem area
            this.genes[i].graphic.loadPixels();
            for (var j=0; j < healthiestGene.numPixels; j++){
                this.genes[i].graphic.pixels[j] = healthiestGene.graphic.pixels[j];
            }
            this.genes[i].graphic.updatePixels();

            if (i!=0) {
                this.genes[i].mutate(); //I mutate every Gene in the array but one
            }
            this.genes[i].evaluateFitness();
        }
    }

目前,我通过逐个像素地设置两个像素阵列彼此相等来实现这一点,但我想知道是否有更有效的方法来做到这一点。我试着简单地写:

this.genes[i].graphic.pixels = healthiestGene.graphic.pixels;

但这并没有起到任何作用。我很乐意就如何将这两个像素阵列设置为彼此相等而不必逐个像素地检查它们提出任何建议。

谢谢!

您可能不想将新实例设置为与旧实例相同,因为这样您对子实例所做的任何更改也会影响父实例。相反,您可能想要复制一份。

您可以创建一个新的图形实例,然后将旧实例绘制到新实例上。像这样:

var pg2 = createGraphics(pg.width, pg.height);
pg2.image(pg, 0, 0);

此时,pg2 将包含 pg 原来的内容。