javascript - 将矩阵数据转换为数组、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);
产生更“稳定”但仍然不正确的东西。
所以我认为这个公式可能是正确的,并且有一些状态更新逻辑没有正确发生。
解决方案
奇怪的行为是固定的。事实证明,在编辑中修复了部分错误,但此外,在计算数组时发生了突变,因此 - 修复是确保始终处理状态确切的索引,而不仅仅是最后一个索引。
推荐阅读
- php - Laravel 根据数据透视表从表中获取标题
- hashtable - TLB 与哈希表有何不同?
- spring - 重置生成 jwt 令牌并更新 spring 安全上下文
- mysql - 不允许 LOAD DATA LOCAL INFILE
- arrays - 这是预期的 Delphi 动态数组行为吗
- java - SLF4J - 基于标签记录到不同的文件
- image - 带有光标图标的 Puppeteer 屏幕截图
- angular - 无法使用任何模拟框架在 Angular 游乐场模拟 ngrx 商店
- python - 如何找到使用 ctypes 从 DLL 文件导入的函数所需的参数?
- r - 颜色在 3D 散点图 (R) 上显示不正确