Advertisement
Guest User

Untitled

a guest
May 19th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. ////////// App.tsx
  2. import React from 'react';
  3. import Animation from './Animation';
  4. import './App.css';
  5.  
  6. const App: React.FC = () => (
  7. <div className="App">
  8. <Animation />
  9. </div>
  10. );
  11.  
  12. export default App;
  13.  
  14. ////////// Animation.tsx
  15. import React, { Component } from 'react';
  16. import PureCanvas from './PureCanvas';
  17.  
  18. let z = 0;
  19.  
  20. class Engine {
  21. ctx: CanvasRenderingContext2D;
  22. frameBuffer: ImageData;
  23. constructor(ctx: CanvasRenderingContext2D) {
  24. this.ctx = ctx;
  25. this.frameBuffer = ctx.createImageData(ctx.canvas.width, ctx.canvas.height);
  26. }
  27. tick = () => {
  28. // Iterate through every pixel
  29. for (let i = 0; i < this.frameBuffer.data.length; i += 4) {
  30. // Modify pixel data
  31. this.frameBuffer.data[i + 0] = z; // R value
  32. this.frameBuffer.data[i + 1] = z; // G value
  33. this.frameBuffer.data[i + 2] = z; // B value
  34. this.frameBuffer.data[i + 3] = 255; // A value
  35. }
  36. z++;
  37. if (z > 255) {
  38. z = 0;
  39. }
  40. };
  41. drawFrame = () => {
  42. this.ctx.putImageData(this.frameBuffer, 0, 0);
  43. };
  44. }
  45.  
  46. interface AnimationState {
  47. frameId: number;
  48. engine: Engine | null;
  49. }
  50.  
  51. class Animation extends Component<any, AnimationState> {
  52. state: AnimationState = {
  53. frameId: 0,
  54. engine: null,
  55. };
  56.  
  57. componentDidMount() {
  58. this.setState({
  59. frameId: requestAnimationFrame(this.updateAnimationState),
  60. });
  61. }
  62.  
  63. saveContext = (ctx: CanvasRenderingContext2D) => {
  64. this.setState({
  65. engine: new Engine(ctx),
  66. });
  67. };
  68.  
  69. updateAnimationState = () => {
  70. const { engine } = this.state;
  71. if (engine) {
  72. // After tick() is finished, we have a frame to draw
  73. engine.tick();
  74. engine.drawFrame();
  75. }
  76. requestAnimationFrame(this.updateAnimationState);
  77. };
  78.  
  79. render() {
  80. return <PureCanvas contextRef={this.saveContext} />;
  81. }
  82. }
  83.  
  84. export default Animation;
  85.  
  86. ////////////////// PureCanvas.tsx
  87.  
  88. import React, { Component } from 'react';
  89.  
  90. interface PureCanvasProps {
  91. contextRef: Function;
  92. }
  93.  
  94. class PureCanvas extends Component<PureCanvasProps, any> {
  95. shouldComponentUpdate() {
  96. return false;
  97. }
  98.  
  99. render() {
  100. return (
  101. <canvas
  102. width="160"
  103. height="144"
  104. ref={node =>
  105. node ? this.props.contextRef(node.getContext('2d')) : null
  106. }
  107. />
  108. );
  109. }
  110. }
  111.  
  112. export default PureCanvas;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement