在react.js项目中运行pixi.js脚本

时间:2018-05-27 17:13:47

标签: javascript reactjs pixi.js

我正在尝试在反应项目中运行pixi.js脚本,但是我被阻止了这个错误:

Cannot read property 'appendChild' of null

我不知道为什么会发生这种错误。我的脚本必须在div中创建一个canvas元素来显示一个带有失真效果的图像:http://guillaumeduclos.fr/ripple-effect/它在基本的HTML和JS环境中运行良好。

Image of TypeError

我的代码:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import image from './image.png';
import * as PIXI from 'pixi.js'

var width = window.offsetWidth;
var height = window.offsetHeight;
var playground = document.getElementById('pxrender');  
var canvas;
var ratio = 150 / 830;
var count = 0;
var raf;

var renderer = PIXI.autoDetectRenderer(width, height,{transparent:true});
renderer.autoResize = true;
var tp, preview;
var displacementSprite,
    displacementFilter,
    stage;

class App extends Component {

  state = {
    playground: null
  }

  componentDidMount() {
    this.setState({playground: this.refs.pxrender});
  }

  setScene = (url) => {
    playground.appendChild(renderer.view);
    stage = new PIXI.Container();
    tp = PIXI.Texture.fromImage(url);
    preview = new PIXI.Sprite(tp);
    preview.anchor.x = 0;
    displacementSprite = PIXI.Sprite.fromImage('https://res.cloudinary.com/dvxikybyi/image/upload/v1486634113/2yYayZk_vqsyzx.png');
    displacementSprite.texture.baseTexture.wrapMode = PIXI.WRAP_MODES.REPEAT;
    displacementFilter = new PIXI.filters.DisplacementFilter(displacementSprite);
    displacementSprite.scale.y = 0.6;
    displacementSprite.scale.x = 0.6;
    stage.addChild(displacementSprite);
    stage.addChild(preview);
    this.animate();
  }

  removeScene = () => {
    cancelAnimationFrame(raf);
    stage.removeChildren();
    stage.destroy(true);
    playground.removeChild(canvas);
  }

  animate = () => {
    raf = requestAnimationFrame(this.animate);
    displacementSprite.x = count*10;
    displacementSprite.y = count*10;
    count += 0.05;
    stage.filters = [displacementFilter];
    renderer.render(stage);
    canvas = playground.querySelector('canvas');
  }

  render() {

    this.setScene(image);

    return (
      <div ref="pxrender" id="pxrender">

      </div>
    );
  }
}

export default App;

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您需要在componentDidMount()而不是render()中启动Pixi应用程序。

this.setScene(image);移至componentDidMount(),如下所示:

componentDidMount() {
    this.setScene(image);
}

有关React中pixi.js场景的完整示例,请看这里:https://github.com/ccnmtl/astro-interactives/blob/master/sun-motion-simulator/src/DatePicker.jsx