首页 > 解决方案 > 将矩阵数据转换为数组、js、奇怪的行为

问题描述

我正在尝试将两个数组的迭代转换为组合数组大小的 4 倍,以制作图像,

example input => [[1][0]]
expected output=> [[255][255][255][255][0][0][0][255]]

((height*width+index)*4) (我尝试过使用和不使用 *4)是我理解为将其转换为 ImageData().data 的 rgba 的公式;

我只写最新的一行,将对 ImageData.data 进行切片/连接/切片,这样我每次绘制只写一行。

预期的视觉效果是二维元胞自动机规则的可视化,一次绘制 1 条线。

实际:奇怪的电路弯曲,脉动模式。

     draw(){
          if(this.height<this.lineNum){ //lineNum is the current y draw line
               this.image.data = this.image.data.slice(this.width*4).join(this.image.data.slice(0,this.width*4)); //cut the begining, put it at the end, then write over it so it moves
          }
          this.nodes.forEach((node,x)=>{ 
               const state = node.lastState(); 
               const index = (((Math.min(this.lineNum,this.height))*x + (node.index))*4);
               this.image.data[index+0]=state?255:0;
               this.image.data[index+1]=state?255:0;
               this.image.data[index+2]=state?255:0;
               this.image.data[index+3]=255;     
          })
          this.ctx.putImageData(this.image ,0,0);  
     }

这是完整的代码,但我确信我的这个公式有误。

上面的代码片段来自第 61 行的 draw 函数。

https://codepen.io/altruios/pen/QWEoYXz?editors=1010

编辑

const index = (((Math.min(node.state.length-1,this.height))*this.width + (node.index))*4);

产生更“稳定”但仍然不正确的东西。

所以我认为这个公式可能是正确的,并且有一些状态更新逻辑没有正确发生。

标签: javascriptmatrixcanvascellular-automataimagedata

解决方案


奇怪的行为是固定的。事实证明,在编辑中修复了部分错误,但此外,在计算数组时发生了突变,因此 - 修复是确保始终处理状态确切的索引,而不仅仅是最后一个索引。


推荐阅读