1.1.1 • Published 10 months ago

@projectleo/tickerjs v1.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

Tickerjs @ProjectLeo · GitHub license npm version bundle size

Tickerjs provides a more easier way to request animation frames.

Installation

npm install @projectleo/tickerjs

Examples

Basic example:

import { requestAnimationFrames } from '@projectleo/tickerjs'

const cancelAnimationFrames = requestAnimationFrames({
    actionOnFrame() {
        console.log(performance.now())
    },
})

setTimeout(cancelAnimationFrames, 5000)

Complicated example:

import {
    twentyFour,
    thirty,
    requestAnimationFrames,
    getStructuredTime,
} from '@projectleo/tickerjs'

/* some code */

const { minute: totalMinutes, second: totalSeconds } = getStructuredTime(
    thirty.second,
    'minute',
)

requestAnimationFrames({
    totalTime: thirty.second,
    frameRate: twentyFour.fps,
    actionOnStart() {
        audioElement.play()
    },
    actionOnFrame({ remainingTime, frameCount }) {
        /* some code */

        const { minute: remainingMinutes, second: remainingSeconds } =
            getStructuredTime(remainingTime, 'minute')

        ctx.drawImage(imageFrames[frameCount], 0, 0)
        ctx.fillText(
            `${remainingMinutes}:${remainingSeconds} / ${totalMinutes}:${totalSeconds}`,
            4,
            20,
        )

        /* some code */
    },
    actionOnEnd() {
        audioElement.pause()
    },
})

APIs

Core function

/**
 * @throws {RangeError} `NaN`, `0`, negative numbers and non-integers are not valid for `totalTime` and `frameRate`.
 * @throws {RangeError} `Infinity` is not valid for `frameRate`.
 */
function requestAnimationFrames({ totalTime, frameRate, actionOnStart, actionOnFrame, actionOnEnd, }: {
    totalTime?:⁰ number;
    frameRate?:¹ number;
    actionOnStart?:² () => void;
    actionOnFrame:³ (args: {
        remainingTime:⁴ number;
        frameCount:⁵ number;
        time:⁶ number;
    }) =>⁷ void | {
        continueHandleFrames: boolean;
    };
    actionOnEnd?:⁸ () => void;
}):⁹ never | (() => void);
  • totalTime: Total time of animation, in milliseconds, if it is not specified, its value is Infinity.
  • ¹ frameRate: Frame rate of animation, if it is not specified, the value of it is usually 60 (fps), but will generally match the display refresh rate in most web browsers as per W3C recommendation.
  • ² actionOnStart: Called when the animation starts.
  • ³ actionOnFrame: Called at every valid frames, it means that not every logical frames could call it if the specified frame rate is higher than display refresh rate.
  • remainingTime: Remaining time of animation, in milliseconds.
  • frameCount: Frame counts calculated from one, it doesn't always increase one by one if the specified frame rate is higher than display refresh rate.
  • time: Same as the parameter of callback for requestAnimationFrame.
  • actionOnFrame(): It could return a value to end the animation in advance, and actionOnEnd would be called.
  • actionOnEnd: Called when the animation ends.
  • requestAnimationFrames(): It would return a function used to cancel remaining animation frames, if use this function, actionOnEnd would not be called.

Time numbers

Tickerjs provides a series of commonly used numerical constants:

NumberObjectPropertyPropertyPropertyPropertyPropertyProperty
1onemillisecondsecondminutehourdayfps
2twomillisecondsecondminutehourdayfps
3threemillisecondsecondminutehourdayfps
5fivemillisecondsecondminutehourdayfps
7sevenmillisecondsecondminutehourdayfps
10tenmillisecondsecondminutehourdayfps
12twelvemillisecondsecondminutehourdayfps
14fourteenmillisecondsecondminutehourdayfps
15fifteenmillisecondsecondminutehourdayfps
20twentymillisecondsecondminutehourdayfps
21twentyOnemillisecondsecondminutehourdayfps
24twentyFourmillisecondsecondminutehourdayfps
25twentyFivemillisecondsecondminutehourdayfps
28twentyEightmillisecondsecondminutehourdayfps
29twentyNinemillisecondsecondminutehourdayfps
30thirtymillisecondsecondminutehourdayfps
31thirtyOnemillisecondsecondminutehourdayfps
45fortyFivemillisecondsecondminutehourdayfps
48fortyEightmillisecondsecondminutehourdayfps
50fiftymillisecondsecondminutehourdayfps
60sixtymillisecondsecondminutehourdayfps
90ninetymillisecondsecondminutehourdayfps
120oneHundredTwentymillisecondsecondminutehourdayfps
144oneHundredFortyFourmillisecondsecondminutehourdayfps
240twoHundredFortymillisecondsecondminutehourdayfps
300threeHundredmillisecondsecondminutehourdayfps
360threeHundredSixtymillisecondsecondminutehourdayfps
500fiveHundredmillisecondsecondminutehourdayfps

If you need other specific values for totalTime of requestAnimationFrames, these functions would be useful:

function second(second: number): number;
function minute(minute: number): number;
function hour(hour: number): number;
function day(day: number): number;

Utility function

type StructuredTimeWithDayUnit = {
    day: number;
    hour: number;
    minute: number;
    second: number;
    millisecond: number;
};

type StructuredTimeWithHourUnit = {
    hour: number;
    minute: number;
    second: number;
    millisecond: number;
};

type StructuredTimeWithMinuteUnit = {
    minute: number;
    second: number;
    millisecond: number;
};

type StructuredTimes = {
    day: StructuredTimeWithDayUnit;
    hour: StructuredTimeWithHourUnit;
    minute: StructuredTimeWithMinuteUnit;
};

const getStructuredTime:
    <T extends keyof StructuredTimes>(totalMilliseconds:⁰ number, highestUnit:¹ T) =>²
    StructuredTimes[T];
  • totalMilliseconds: Total time to be structured, in milliseconds.
  • ¹ highestUnit: The highest unit to be used when structuring time, you can only choose one from 'day', 'hour' and 'minute'.
  • ² getStructuredTime(): It would return an object that contains structured time fields, fields are based on specified highestUnit.

Troubleshooting

⚠️ After I unpacking values from time numbers, some strange errors are thrown.

Time numbers are proxy values, not pure objects, don't use destructuring assignment syntax on them.

⚠️ Animation sometimes would end before reaching expected frame counts.

If the total time of animation is specified, animation would always end when remaining time is exhausted. Depending on the refresh rate of display, if the specified frame rate is higher than display refresh rate, animation may end before reaching expected frame counts because of the runtime's calculation accuracy error.

⚠️ When I use tickerjs in some browsers directly, some errors are thrown.

Tickerjs uses some latest JavaScript features in source code, the exported bundle also has not been processed by JavaScript compiler like Babel, you need to handle it yourself.

FAQ

// without tickerjs

function callback(time) {
    doSomething(time)

    requestAnimationFrame(callback)
}

requestAnimationFrame(callback)

// with tickerjs

requestAnimationFrames({
    actionOnFrame({ time }) {
        doSomething(time)
    },
})

License

Tickerjs is MIT licensed.

1.1.1

10 months ago

1.1.0

12 months ago

1.0.0

12 months ago