Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ////////// App.tsx
- import React from 'react';
- import Animation from './Animation';
- import './App.css';
- const App: React.FC = () => (
- <div className="App">
- <Animation />
- </div>
- );
- export default App;
- ////////// Animation.tsx
- import React, { Component } from 'react';
- import PureCanvas from './PureCanvas';
- let z = 0;
- class Engine {
- ctx: CanvasRenderingContext2D;
- frameBuffer: ImageData;
- constructor(ctx: CanvasRenderingContext2D) {
- this.ctx = ctx;
- this.frameBuffer = ctx.createImageData(ctx.canvas.width, ctx.canvas.height);
- }
- tick = () => {
- // Iterate through every pixel
- for (let i = 0; i < this.frameBuffer.data.length; i += 4) {
- // Modify pixel data
- this.frameBuffer.data[i + 0] = z; // R value
- this.frameBuffer.data[i + 1] = z; // G value
- this.frameBuffer.data[i + 2] = z; // B value
- this.frameBuffer.data[i + 3] = 255; // A value
- }
- z++;
- if (z > 255) {
- z = 0;
- }
- };
- drawFrame = () => {
- this.ctx.putImageData(this.frameBuffer, 0, 0);
- };
- }
- interface AnimationState {
- frameId: number;
- engine: Engine | null;
- }
- class Animation extends Component<any, AnimationState> {
- state: AnimationState = {
- frameId: 0,
- engine: null,
- };
- componentDidMount() {
- this.setState({
- frameId: requestAnimationFrame(this.updateAnimationState),
- });
- }
- saveContext = (ctx: CanvasRenderingContext2D) => {
- this.setState({
- engine: new Engine(ctx),
- });
- };
- updateAnimationState = () => {
- const { engine } = this.state;
- if (engine) {
- // After tick() is finished, we have a frame to draw
- engine.tick();
- engine.drawFrame();
- }
- requestAnimationFrame(this.updateAnimationState);
- };
- render() {
- return <PureCanvas contextRef={this.saveContext} />;
- }
- }
- export default Animation;
- ////////////////// PureCanvas.tsx
- import React, { Component } from 'react';
- interface PureCanvasProps {
- contextRef: Function;
- }
- class PureCanvas extends Component<PureCanvasProps, any> {
- shouldComponentUpdate() {
- return false;
- }
- render() {
- return (
- <canvas
- width="160"
- height="144"
- ref={node =>
- node ? this.props.contextRef(node.getContext('2d')) : null
- }
- />
- );
- }
- }
- export default PureCanvas;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement