Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/ivanross/use-tela
https://github.com/ivanross/use-tela
animation canvas hook react
Last synced: 16 days ago
JSON representation
- Host: GitHub
- URL: https://github.com/ivanross/use-tela
- Owner: ivanross
- License: mit
- Created: 2021-12-27T09:19:15.000Z (about 3 years ago)
- Default Branch: main
- Last Pushed: 2022-01-03T15:22:16.000Z (about 3 years ago)
- Last Synced: 2024-11-06T08:37:53.244Z (2 months ago)
- Topics: animation, canvas, hook, react
- Language: TypeScript
- Homepage:
- Size: 377 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# use-tela
## Installation
```sh
# Yarn
yarn add use-tela# NPM
npm install use-tela
```## Usage
`useTela` provides functionality to draw on a canvas.
It requires to pass a width and a height value. The hook scales
the canvas based on passed dimensions and the device displayPixelRatio.The core functionality can be accessed by setting the `draw`
attribute: it is a callback that accepts a `TelaEvent`. If
`loop` is set to `true`, draw function will be called for every
animation frame, otherwise it will be called once.```jsx
import { useTela } from "use-tela"const App = () => {
const ref = useTela({
width: 400,
height: 400,
loop: true,draw: (event) => {
const ctx = event.canvas.getContext("2d")
...
}
})
return
}
```In order to bind the hook to a canvas, you can pass a ref
```js
const ref = useRef()
useTela({ ref, ... })
return
```or use the returned one:
```js
const ref = useTela({ ... })
return
```## Options
```ts
interface TelaOptions {
/** Tela width */
width: number;
/** Tela height */
height: number;
/** Max devicePixelRatio value. Default is `4` */
maxDpr?: number;/**
* Ref holding the canvas element. If you omit
* it, `useTela` will create and return one for you
*/
ref?: React.RefObject;/** Enables drawing loop when `true`. Default is `false` */
loop?: boolean;/**
* Callback called for every loop frame (when `loop` is `true`)
* and when the canvas resizes
*/
draw?: (ev: TelaEvent) => void;
/**
* Callback called when the canvas resizes
*/
onResize?: (ev: TelaEvent) => void;
}
```## Event
Event passed to `useTela` callbacks (see `draw` or `onResize`).
It holds informations about the canvas, the loop (such as elapsed time)
and user interaction (such as mouse position).```ts
interface TelaEvent {
/** The canvas DOM element */
canvas: HTMLCanvasElement;
/** Tela width */
width: number;
/** Tela height */
height: number;
/** Elapsed time from first `useTela` call */
time: number;
/** Mouse position */
mouse: Point2;
}
```