由于TypeError而无法渲染Canvas:无法读取属性' getImageData'为null

时间:2018-06-13 19:24:09

标签: javascript reactjs

我正在尝试使用反应应用程序来渲染conways life方法。我仍然对React.js有点新意,希望有人可以解释为什么我的代码被破坏以及如何修复它。也许如何防止它在未来发生。以下是我的代码

import React, { Component } from 'react';
import Life from './life';
import './App.css';

/**
 * Life canvas
 */
class LifeCanvas extends Component {
  /**
   * Constructor
   */
  constructor(props) {
    super(props);

    this.life = new Life(props.width, props.height);
    this.life.randomize();
  }

  /**
   * Component did mount
   */
  componentDidMount() {
    requestAnimationFrame(() => {
      this.animFrame();
    });
  }

  /**
   * Handle an animation frame
   */
  animFrame() {
    //
    // !!!! IMPLEMENT ME !!!!
    //
    let width = this.props.width;
    let height = this.props.height;

    // Request another animation frame
    // Update life and get cells
    let cells = this.life.getCells();

    // Get canvas framebuffer, a packed RGBA array
    let canvas = this.refs.canvas;
    let ctx = canvas.getContext('2D');
    let imageData = ctx.getImageData(0, 0, width, height);

    // Convert the cell values into white or black for the canvas
    for (let y = 0; y < height; y++) {
      for (let x = 0; x < width; x++) {
        let index = (y * width + x) * 4;

        let lifeStatus = cells[y][x];
        let color = lifeStatus === 0 ? 0xff : 0x00;

        imageData.data[index + 0] = color; // R
        imageData.data[index + 1] = color; // G
        imageData.data[index + 1] = color; // B
        imageData.data[index + 1] = color; // A
      }
    }
    // Put the new image data back on the canvas
    ctx.putImageData(imageData, 0, 0);

    // Next generation of life
    this.life.step();
    requestAnimationFrame(() => {
      this.animFrame();
    });
  }

  /**
   * Render
   */
  render() {
    return (
      <canvas
        ref="canvas"
        width={this.props.width}
        height={this.props.height}
      />
    );
  }
}

/**
 * Life holder component
 */
class LifeApp extends Component {
  /**
   * Render
   */
  render() {
    return (
      <div>
        <LifeCanvas width={600} height={600} />
      </div>
    );
  }
}

/**
 * Outer App component
 */
class App extends Component {
  /**
   * Render
   */
  render() {
    return (
      <div className="App">
        <LifeApp />
      </div>
    );
  }
}

export default App;

当它呈现页面时,主题行中的错误以大红色字母生成。我不确定这意味着什么。请帮忙。

1 个答案:

答案 0 :(得分:0)

ctxnull。当传递的上下文类型无效时,getContext()将返回null。在您的情况下,您通过了2D the proper context type string is 2d

var c = document.createElement('canvas');
var ctx = c.getContext('2D');
console.log("ctx is: ",ctx);

ctx = c.getContext('2d');
console.log("ctx is now: ",ctx);