简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM