AnimationCanvas
A simple animatable canvas with requestAnimationFrame()
Import
import { AnimationCanvas } from '@tremolo-ui/react'
Features
- Adapt devicePixelRatio.
- Reduce flicking when resized.
Examples
Basic
Loading...
function App() { return ( <AnimationCanvas width={200} height={200} init={(ctx) => { ctx.font = '16px sans-serif' }} draw={(ctx, { width, height, count }) => { ctx.clearRect(0, 0, width, height) ctx.fillText(`frame: ${count}`, 0, 16) // draw sine wave const halfH = height / 2 ctx.strokeStyle = '#29bbf0' ctx.beginPath() for (let i = 0; i < width; i++) { const y = halfH + halfH * 0.5 * Math.sin((4 * Math.PI * (i + count * 2)) / width) if (i == 0) ctx.moveTo(i, y) else ctx.lineTo(i, y) } ctx.stroke() }} /> ) }
Save / Restore
Loading...
function App() { return ( <div style={{ width: 300, height: 200, }} > <AnimationCanvas relativeSize draw={(ctx, { width, height, elapsedTime, count }) => { // save default context ctx.save() ctx.clearRect(0, 0, width, height) ctx.fillStyle = 'gray' ctx.fillRect(40, 40, 30, 30) // change scale ctx.scale(2, 2) ctx.fillStyle = 'red' ctx.fillRect(40, 40, 30, 30) // restore default context ctx.restore() ctx.fillStyle = 'black' ctx.font = '16px sans-serif' ctx.fillText( `frame: ${count}, ${(elapsedTime / 1000).toFixed(2)} s`, 0, 16, ) }} /> </div> ) }
Reactive Canvas
React.useState
+ animate={false}