Repository navigation
Description
The problem is clearly described in
- Add BoundingClientRectObserver #9104
- UPDATE: new issue specifically describing the problem and possible solutions: [resize-observer] why we need
ResizeObserver.takeRecords()orResizeObserver.hasRecords()(the canvas flickering problem) w3c/csswg-drafts#9717
but I'll paste it here too (click to expand):
But there's a problem with adding new
*Observerpatterns in general:We have no way to derive state from multiple combinations of them for use in the browser paint cycle.
The more
*ObserverAPIs we add, the more need we have for some way to run logic after all paint-cycle observers have ran (by paint-cycle observers, I mean those that run in sync with animation frames and browser paint).Here's the problem, which add yet another frame-based
*Observerwill exacerbate:At present, if we rely on an animation frame, a
ResizeObserver, aMutationObserver, and anIntersectionObserver, in order to react to changes of all of those, and to derive all the state we need for rendering something to a WebGL canvas, this means we will have to render to the canvas a total of 4 times in one frame, reducing our framerate to 25% (ouch!!!!!). In each callback, starting with the animation frame callback, we have to update state and then render.We must render in every type of callback, because we don't know, for any given render frame, which callbacks will run.
If we render to canvas only in an animation frame callback (which is essentially the pattern that everyone (and I mean practically everyone) is writing today), we'll run into unintuitive issues like this one where on every resize the canvas will flicker (typically a white color on websites with default CSS background).
Here's a demo. Set
SHOW_FLICKER_PROBLEMtotrueto see the issue here:https://codepen.io/trusktr/pen/EzBKYM
Here's what the problem looks like:
flicker.mov
Then set
SOLVE_FLICKER_PROBLEMtotrueto enable the solution, and the problem will be gone:no-flicker.mov
Note the comments, which will point out where the canvas is double rendered during resize, cutting the framerate of a resize in half (ouch!!). Resizing browser windows is typically sluggish already, and this will make things worse.
This problem happens because if we resize a canvas in a
ResizeObservercallback after we have already rendered in an animation frame callback (animation frame callbacks always fire before ResizeObserver callbacks) and do not render again in the resize observer callback, then the canvas pixels will be cleared. The pixel clearing is a natural consequence of resizing a canvas and has nothing to do with animation frames or resize observers, however the way these APIs work, we do not have a reliable way to handle certain state changes after multiple callback groups (anim frames, observer callbacks).The only way to get around all issues with aimation frames and *Observer APIs with simple code is to resort to polling for all state in a single animation frame callback, but with the added performance cost of unnecessarily reading state every frame (although in some cases this can be faster than double rendering).
To avoid polling, the solution would be very complicated, requiring use of
MutationObserverto detect every possible change in the DOM that could possibly a client rect to change (there are many many possibly ways to change a client rect including<style>content changes,styleattribute changes including of parents and children, inside and outside of shadow roots, etc, it gets really really complicated to do it robustly without missing any cases).TLDR
Yes, new APIs like
ClientRectObserver(I think this name is fine without "Bounding" in it) would be nice, but we also need a way to run final logic after all frame-based*Observercallbacks so that adding yet more*ObserverAPIs doesn't make the above issue worse.For example, maybe something like this:
requestAnimationFrame(function loop() { // ... update things like position/rotation of objects, etc ... requestAnimationFrame(loop) }) new ResizeObserver(() => {...}).observer(el) new ClientRectObserver(() => {...}).observer(el) new MutationObserver(() => {...}).observer(el) // microtask, irrelevant to render loop requestFinalFrame(function finalLoop() { // This runs after everything, even frame-based *Observer APIs added in the future. // ... calculate final state, finally render to canvas a SINGLE time ... requestFinalFrame(finalLoop) })Every render cycle of the browser, callbacks would be called in roughly this order:
- animation frame callbacks (do not render to canvas here)
- *Observer callbacks in some particular order, but we should not rely on the order, just collect needed state.
- final callbacks (derive final state, render to canvas, etc)
Solution
Something like requestFinalFrame()would allow running a frame after animation frame callbacks and *Observer callbacks (including callbacks of any frame-based *Observer APIs added in the future, and potentially any other type of frame-based callbacks added in the future that currently don't exist), so that final state and rendering can be performed in a consistent manner without duplication of final state derivation or rendering logic (see the problem and codepen example in the other issue).
// in the next browser render frame, the given callback will run *after* animation frame
// callbacks and `*Observer` callbacks such as for ResizeObserver, allowing us to perform
// final tasks such as rendering final derived state to a canvas:
requestFinalFrame(() => {
// ... render to canvas a *single* time *after* all state, including canvas size, is derived ...
})
Activity
[-]We need something like `requestFinalFrame()` to run logic after all *Observer callbacks[/-][+]We need something like `requestFinalFrame()` to run logic after all `*Observer` callbacks[/+]annevk commentedon Sep 11, 2023
I don't understand why you can't schedule updates and make them during
requestAnimationFrame.Also, this would benefit a lot from reading through https://whatwg.org/faq#adding-new-features and applying it. Thanks!
trusktr commentedon Dec 17, 2023
@annevk Wish it was that easy! Some observer APIs that run callbacks between rAF and browser paint (f.e.
ResizeObserver, and potentially new observer APIs likeBoundingClientRectObserverandComputedStyleObserver) introduce the problem described in the following issue (examples included):ResizeObserver.takeRecords()orResizeObserver.hasRecords()(the canvas flickering problem) w3c/csswg-drafts#9717With
requestFinalFrame(orrequestPaintFrameor some similar named API), the convention for web developers would become:requestAnimationFrameResizeObservercallbacks)requestFinalFrame(orrequestPaintFrameor whatever name we come up with) to draw/render a single time, f.e. resizing a canvas and finally sending WebGL draw commands.greggman commentedon Jan 19, 2024
Hadn't seen this thread, posted some solutions here
https://stackoverflow.com/questions/77842752/how-do-i-use-resizeobserver-with-requestanimationframe-correctly
Kaiido commentedon Jan 19, 2024
One problem I can see with yet another callback in the event-loop, it that the changes made in that callback would get missed by all these observers. Then we'll want a
FinalObserverof some sort to tackle these, etc.I feel the best would be to have a way to limit the possible actions in this hook to compositing related actions only, so maybe a
WorkletlikePaintWorkletwould actually be the best place for such updates, though the limited API of this latter is certainly an issue.StephenHaney commentedon Nov 27, 2024
Ah just found this thread too – @trusktr you read my mind!
I would love to be able to draw to WebGL/Canvas after layout and observer callbacks.
The sequencing I would love as an app-builder:
Without the proposed API, my draw calls are done in the rAF and are always one frame behind the DOM layout.
I'd assume that DOM changes made in this callback would not process until the next frame (or could even error, etc)
I am very likely missing some nuance here. I just wanted to help demonstrate why this sequencing is important in app-builder-land. I make design tools in the browser and often use a full screen canvas layered over top of DOM to draw selections and highlights.
StephenHaney commentedon Dec 4, 2024
I created a loopBeforePaint helper repo as a workaround solution.
It triggers a ResizeObserver callback on every frame so that the developer gets a callback that runs reliably after layout but before paint.
So far this is working well for me, but there are some considerations:
Edit: Kaiido provided a better implementation below so I updated the code in the repo.
Original method, no longer used: It originally placed a div into the document, observed it with an RO, and used a rAF to resize it each frame.
Kaiido commentedon Dec 4, 2024
@StephenHaney you don't need an rAF loop nor to dirty your layout by resizing this div.
ResizeObserver.observe()will queue the RO's observer when it's disconnected, so you just need to disconnect it in the callback and callobserve()when you need to hook to the next frame.For reference below is a
waitBrowserReflowfunction I use, but note that your points about trashing the layout in this callback and possibly not being the last such callback still stand and thus can't be a proper bullet proof solution for the use case here.StephenHaney commentedon Dec 4, 2024
Ah thank you – I'll test this in my use case, which needs it every frame, and update the code in the repo to avoid the rAF and layout.
Edit: confirmed that the
.disconnectmethod is working and does not trigger a layout. I updated the code in the repo above.