0

I have a function than takes in a polar equation and plots it pixel by pixel.
The whole loop is finished then it's rendered at the end, but I don't want it to wait till the end of the loop to show the full thing, I just want to show each pixel as it's being rendered one by one.
Most solutions talk about refreshing the whole thing and rerendering the previous stuff, which seems inefficient and also kinda complicated.

Is there a function or technique that could help me accomplish that without too much complication? Maybe something like:

do {
   putPixel(x,y, color);
   renderNow();
   wait();
} while ...
CCC
  • 2,642
  • 7
  • 40
  • 62

1 Answers1

1

You could use requestAnimationFrame and then draw one pixel each frame while incrementing x.

Here's a fiddle of how it would work in general:

https://jsfiddle.net/x7jyob3u/1/

And documentation for requestAnimationFrame

https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

Marko
  • 114
  • 4
  • that seems to change the loop into recursion. Is there a way to avoid that? and it seems requestAnimationFrame only takes a function without parameters, which means doing more changes – CCC Aug 23 '21 at 23:38
  • Yes, there's a way to cancel animation frames. See here: https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame – Marko Aug 26 '21 at 09:51
  • 1
    RAF [isn't recursive](https://stackoverflow.com/questions/29181253/is-requestanimationframe-implementations-recursive/66736179#66736179) and you can pass params to the callback by wrapping your inner func with the params you want. In general, when you're animating, clear the whole thing and redraw it on every frame. Don't worry about efficiency prematurely. That said, a lot of conversions of sketches like [this](https://stackoverflow.com/a/68503939/6243352) don't require clears, since you're essentially drawing one frame/images, only in small stages. – ggorlen Aug 27 '21 at 01:14