开发者

JavaScript optimization with nested loops

I have a huge array of points to draw on a canvas. Right now i am drawing every point by running a nested loop for x and y on the array of the data. This seems to be causing firefox to show a script has hanged notice.

What would be the best way to avoid that?

IMO some kind of parallel 开发者_如何学运维looping solution would be great, but the problem is i am not aware of any such method.


If you're just creating an image pixel by pixel, you're way better off doing it in an "image data" object and then dropping that into the canvas when you're done. It's much, much cheaper to drop pixels into an array than it is to make canvas API calls pixel-by-pixel.

There's a method called "createImageData()" that you use to make an ImageData object, which is really just an array of pixels with height/width. The pixels are organized as a simple linear array, with each group of four array elements representing a single pixel. The four values are just the red, green, and blue color values, and an alpha value for opacity.

When your code has filled in all the pixel values, you just call "putImageData()" to draw it to the canvas.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜