Flip clock from a time element
The clock is one <time> element drawn by a canvas. A timer changes its text once a second. Each change fires paint, and the canvas flips the digits that differ from a snapshot of
the old text to the new text. The page has no frame loop: the frames of a flip come from a CSS animation on the element. Change the time zone to flip most of the digits at once.
Show the code a timer, a snapshot and a CSS animation; no requestAnimationFrame
- The clock. A
<time>element with the digits and a date line. - The styles. A registered property
--flip, and a border colour computed from it. - Once a second. Take a snapshot, change the text, start the animation.
- On
paint. Read--flipand draw each changed digit part way between the snapshot and the element. - One flap part way through a flip.
How it works
A setTimeout() aimed at the start of each second formats the time and compares it with the element's text. When they differ it does three things: it calls captureElementImage() to keep a picture of
the element as it is, it sets the new text and the datetime attribute, and it starts a Web Animation that runs the registered custom property --flip from 0 to 1 in 520 ms.
The text change fires paint. The animation fires paint on every frame while it runs, because the element's top border has a colour computed from --flip. The paint handler reads
--flip with getComputedStyle() and uses it as the progress of the flip. For each digit that changed, the old face is a piece of the snapshot and the new face is a piece of the live element.
When the animation ends the paint events stop, and nothing runs until the next second.
The line under the controls counts the paint events and the calls the page made. requestPaint() is called when the canvas changes size and when it scrolls into the window, and not for the clock.
Live checks
These run on their own fixtures in the corner of the window, after a tap on the button.
Findings
- Changing the text of a
<time>element firespaint. A clock that shows seconds gets one paint event a second from the text alone. - An animation on a registered custom property fires no
paintby itself. With a border colour computed from the property,paintfires once per frame of the animation, andgetComputedStyle()inside the handler returns the interpolated value. That gives a canvas an animation clock with norequestAnimationFrame()and norequestPaint(). - A CSS counter animated with
@keyframesand shown throughcontent: counter()firespaintfor each new number. No script changes the text. captureElementImage()works in a timer, outside a paint handler, and returns the picture from the last paint.- Not verified: Chrome 159 for Android, and whether the timer and the animation keep in step when the phone throttles a page. Watch the status line for a minute: the paint count should rise by about 32 a second with seconds on.