1

我写了一个方法,用于在画布图像数据阵列转换成一个多维坐标基于阵列像这样:的Javascript图像数据以多维数组的性能问题

parse: function() { 
    var x = y = 0; 
    var step = 0; 
    for(var i = 0; i <= this.imageData.length - 4; i += 4) { 
     if(step == this.width) { 
      ++ y; 
      step = 0; 
     } 
     this.data[x][y] = [this.imageData[i], 
          this.imageData[i+1], 
          this.imageData[i+2], 
          this.imageData[i+3]]; 

     ++ x; 
     ++ step; 
    } 
} 

我已经测试了它在较小的规模(10×10图像),但是当我移动到一个更大的图像,在我的情况下800x800,它完全崩溃的浏览器(选项卡)。我可以理解为什么,但是,我想知道是否有更有效的方法来解决这个问题。

有什么想法?

回答

2

你可以通过这样的取%(模数)运营商的优势,少做一些数学:

var floor = Math.floor; // store a reference to Math.floor, anything goes when you have 640,000 iterations 

parse: function(imageHeight, imageWidth) { 
    for(var i = 0; i < this.imageData.length; i++) { 
     this.data[i % imageWidth][Math.floor(i/imageHeight)] = [this.imageData[i], 
          this.imageData[i+1], 
          this.imageData[i+2], 
          this.imageData[i+3]]; 

    } 
}​ 

你必须拿出值imageHeightimageWidth,当然。

+1

我真的很喜欢这个解决方案,但是我似乎正在获取未定义的数据'console.log(this.data [0] [360]);'我期望的数组。有什么想法吗? – grep

+0

啊,这个解决方案似乎不正确地增加了数组。它增加每四个像素是'this.data [0] [0],this.data [4] [0],this.data [8] [0] etc ..' – grep

+0

啊哈,这样做。顺便说一句,我已经更新了我的答案,以便将最后一点速度从for循环中排除。 :)让我看看是否可以看到迭代中出现了什么问题。 –