Javascript 画布未在reactjs中渲染

Javascript 画布未在reactjs中渲染,javascript,html,css,reactjs,canvas,Javascript,Html,Css,Reactjs,Canvas,我想在我正在开发的网站上添加画布,但我似乎能理解为什么画布没有出现。可能是什么问题 下面是我试过的。当我将鼠标悬停在标题上时,它显示画布正在更新,但没有在屏幕上显示任何内容 Canvas.jsx export class Canvas extends Component { state = { container: document.getElementById('test'), canvas: document.createElement('canvas'), c

我想在我正在开发的网站上添加画布,但我似乎能理解为什么画布没有出现。可能是什么问题

下面是我试过的。当我将鼠标悬停在标题上时,它显示画布正在更新,但没有在屏幕上显示任何内容

Canvas.jsx


export class Canvas extends Component {
  state = {
    container: document.getElementById('test'),
    canvas: document.createElement('canvas'),
    ctx: document.createElement('canvas').getContext("2d"),
    mouseCoords: null,
    particles: [],
    width: 0,
    height: 0,
  };

  componentDidMount() {
    window.scrollTo(0, 0);
    document.getElementById('test').appendChild(document.createElement('canvas'));
    this.setState({
      container: document.getElementById('test'),
      canvas: document.createElement('canvas'),
      ctx: document.createElement('canvas').getContext("2d")
    }, () => this.handleResize());
    window.addEventListener("resize", this.handleResize)
  }

  r = (e, t) => {
    return Math.hypot(t[0] - e[0], t[1] - e[1])
  };

  i = (e, t, o, s) => {
    var n = e / s - 1;
    return o * (n * n * (2.2 * n + 1.2) + 1) + t
  };

  componentDidUpdate(prevProps, prevState, snapshot) {
    return null;
  }

  componentWillUnmount() {
    this.setState({
      canvas: document.getElementById('test').remove(),
    });
  }


  handleAnimate = () => {
    var e = this.state;
    var that = this;
    if (!(e.width < 800 * window.devicePixelRatio)) {
      var t = e.particles[e.particles.length - 1]
        , o = (e.width - t.coords.ref[0]) / 2
        , s = t.coords.ref[0]
        , n = (e.height - t.coords.ref[1]) / 2
        , a = t.coords.ref[1];
      e.ctx.clearRect(o, n, s, a);
      e.particles.forEach((t) => {
        t.timer += 1;
        const o = Math.max(that.r(t.coords.ref, e.mouseCoords), 150);
          s = t.coords.ref[0] + (e.mouseCoords[0] - t.coords.ref[0]) / (o / e.width * 150);
          n = t.coords.ref[1] + (e.mouseCoords[1] - t.coords.ref[1]) / (o / e.height * 150);
          a = 150 * t.r.ref / o + .5;
        /* eslint-disable */
        s === t.coords.new[0] && n === t.coords.new[1] || (t.coords.old = t.coords.current.slice(), t.coords.new = [s, n], t.r.old = t.r.current, t.r.new = a, t.timer = 1);
        t.timer < 75 && (t.coords.current[0] = that.i(t.timer, t.coords.old[0], t.coords.new[0] - t.coords.old[0], 75),
          t.coords.current[1] = that.i(t.timer, t.coords.old[1], t.coords.new[1] - t.coords.old[1], 75),
          t.r.current = Math.max(that.i(t.timer, t.r.old, t.r.new - t.r.old, 75), 0));
          e.ctx.fillStyle = t.fill;
          e.ctx.beginPath();
          e.ctx.arc(t.coords.current[0], t.coords.current[1], t.r.current, 0, 2 * Math.PI);
          e.ctx.fill()
      });
      this.setState({
        loop: requestAnimationFrame(this.handleAnimate)
      })
    }
  };

  handleHover = (e) => {
    this.state.mouseCoords = [e.clientX * window.devicePixelRatio, e.clientY * window.devicePixelRatio]
  };


  handleResize = () => {
    const {canvas} = this.state;
    var particle = [];
    let newWidth = window.innerWidth * window.devicePixelRatio,
      newHeight = window.innerHeight * window.devicePixelRatio;

    canvas.height = newHeight;
    canvas.width = newWidth;

    this.setState({
      width: window.innerWidth * window.devicePixelRatio,
      height: window.innerHeight * window.devicePixelRatio,
      canvas,
      mouseCoords: [0, newHeight]
    });

    var e = Math.max(newHeight / 21, 40),
      t = Math.floor(newWidth / (e + 5)),
      o = Math.floor(newHeight / (e + 10)) || 90,
      V = [2, 2, 6, 6, 5, 5, 3, 3, 0, 0, 2, 2, 0, 0],
      j = [[2, 0, 0, 2, 1, 0, 0, 3], [1, 0, 2, 2, 0, 0, 2], [2, 2, 2, 2, 3, 0, 1, 0, 0], [1, 0, 2, 2, 0, 0, 2, 2, 0], [2, 0, 1, 2, 2, 0, 2, 0, 1, 2, 2, 1, 0, 0], [0, 2, 2, 0, 3, 1, 2, 1, 2, 0, 1, 2, 2, 0], [1, 2, 1, 1, 0, 2, 2, 0, 0, 1, 2, 1, 0, 1], [2, 1, 1, 0, 0, 0, 2, 2, 1, 1, 1, 1], [2, 0, 2, 0, 0, 0], [0, 0, 0, 2, 0, 0], [0, 2, 0, 0, 0, 0, 0], [0, 0, 0, 2, 0, 0], [0, 0, 0, 0, 2, 0], [0, 0, 0, 2, 0, 0]];
    console.log(t);


    for (let s = 0; s < o; s += 1) {
      for (var n = 0; n < t; n += 1) {
        var a = Math.round(this.state.width / 2 - e / 2 * (t - 1) + n * e),
          d = Math.round(this.state.height / 2 - e / 2 * (o - 1) + s * e),
          l = "#555555",
          r = e / 20;
        if (s > 0 && s < j.length + 1)
          switch (j[s - 1][t - n - V[s - 1] - 1]) {
            case 0:
              l = "#1DCA7F";
              r = e / 2.5;
              break;
            case 1:
              l = "#047870";
              r = e / 4;
              break;
            case 2:
              l = "#FFFFFF";
              break;
            case 3:
              l = "#6898ae";
              r = e / 2.5
          }
        var i = {
          coords: {
            ref: [a, d],
            current: [a, d],
            new: [a, d],
            old: [a, d]
          },
          r: {
            ref: r,
            current: 0,
            new: r,
            old: 0
          },
          fill: l,
          timer: 1
        };
        particle.push(i);
      }
    }
    this.setState({
      particles: particle
    })
  };

  render() {
    // className="-content-wrapper header"
    return (
      <div className="home">
        <header id="test" onMouseEnter={() => this.handleAnimate()}
                onMouseMove={e => this.handleHover(e)}>
        </header>
      </div>
   )}
}


导出类画布扩展组件{
状态={
容器:document.getElementById('test'),
画布:document.createElement(“画布”),
ctx:document.createElement('canvas').getContext(“2d”),
mouseCoords:null,
粒子:[],
宽度:0,
高度:0,,
};
componentDidMount(){
滚动到(0,0);
document.getElementById('test').appendChild(document.createElement('canvas'));
这是我的国家({
容器:document.getElementById('test'),
画布:document.createElement(“画布”),
ctx:document.createElement('canvas').getContext(“2d”)
},()=>this.handleResize());
window.addEventListener(“resize”,this.handleResize)
}
r=(e,t)=>{
返回Math.hypot(t[0]-e[0],t[1]-e[1])
};
i=(e,t,o,s)=>{
var n=e/s-1;
返回o*(n*n*(2.2*n+1.2)+1)+t
};
componentDidUpdate(prevProps、prevState、快照){
返回null;
}
组件将卸载(){
这是我的国家({
画布:document.getElementById('test').remove(),
});
}
handleAnimate=()=>{
var e=该状态;
var=这个;
如果(!(e.宽度<800*窗口设备比例)){
var t=e.particles[e.particles.length-1]
,o=(e.width-t.coords.ref[0])/2
,s=t.coords.ref[0]
,n=(e.height-t.coords.ref[1])/2
,a=t.coords.ref[1];
e、 ctx.clearRect(o,n,s,a);
e、 粒子。forEach((t)=>{
t、 定时器+=1;
const o=Math.max(that.r(t.coords.ref,e.mouseCoords),150);
s=t.coords.ref[0]+(e.mouseCoords[0]-t.coords.ref[0])/(o/e.width*150);
n=t.coords.ref[1]+(e.mouseCoords[1]-t.coords.ref[1])/(o/e.height*150);
a=150*t.r.ref/o+.5;
/*eslint禁用*/
s===t.coords.new[0]&&n==t.coords.new[1]| |(t.coords.old=t.coords.current.slice(),t.coords.new=[s,n],t.r.old=t.r.current,t.r.new=a,t.timer=1);
t、 timer<75&(t.coords.current[0]=that.i(t.timer,t.coords.old[0],t.coords.new[0]-t.coords.old[0],75),
t、 coords.current[1]=that.i(t.timer,t.coords.old[1],t.coords.new[1]-t.coords.old[1],75),
t、 r.current=Math.max(即.i(t.timer,t.r.old,t.r.new-t.r.old,75),0));
e、 ctx.fillStyle=t.fill;
e、 ctx.beginPath();
e、 ctx.arc(t.coords.current[0],t.coords.current[1],t.r.current,0,2*Math.PI);
e、 ctx.fill()
});
这是我的国家({
循环:requestAnimationFrame(this.handleAnimate)
})
}
};
handleHover=(e)=>{
this.state.mouseCoords=[e.clientX*window.devicePixelRatio,e.clientY*window.devicePixelRatio]
};
handleResize=()=>{
const{canvas}=this.state;
var粒子=[];
设newWidth=window.innerWidth*window.devicePixelRatio,
newHeight=window.innerHeight*window.devicePixelRatio;
canvas.height=新高度;
canvas.width=newWidth;
这是我的国家({
宽度:window.innerWidth*window.devicePixelRatio,
高度:window.innerHeight*window.devicePixelRatio,
帆布,
鼠标文字:[0,新高度]
});
变量e=数学最大值(新高度/21,40),
t=数学楼层(新宽度/(e+5)),
o=数学楼层(新高度/(e+10))| | 90,
V=[2,2,6,6,5,5,3,3,0,0,2,2,0,0],
0,2,2,2,0,0,0,0,0,3,[1,0,2,2,0,0,2,[2,2,2,2,2,2,2,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 2,0,0,0],[0,0,0,2,0,0],[0,2,0,0,0,0,0,0],[0, 0, 0, 2, 0, 0], [0, 0, 0, 0, 2, 0], [0, 0, 0, 2, 0, 0]];
控制台日志(t);
对于(设s=0;s0&&sthis.handleHover(e)}>
)}
}
我想要实现的是一个带有粒子的画布。悬停时,粒子应朝光标指向的方向移动,并缩放绿色粒子。您可以使用refs(请注意,facebook不鼓励在大多数情况下使用refs,请参阅)

我会这样做:

export class Canvas extends React.Component {
  constructor(props) {
    super(props);
    this.canvas = React.createRef();
    this.context = null // this will be initializaed in componentDidMount()
  }

  componentDidMount(){
    this.context = this.canvas.getContext("2d")
  }

  ...

  render() {
    return (
      <div className="home">
        <header id="test" onMouseEnter={() => this.handleAnimate()}
                onMouseMove={e => this.handleHover(e)}>
        </header>
        <canvas ref={this.canvas} className={style.canvas}/>
        <!-- Make sure to size the canvas correctly using CSS -->
      </div>  
  )}
}
导出类画布扩展React.Component{
建造师(道具){
超级(道具);
this.canvas=React.createRef();
this.context=null//这将在componentDidMount()中初始化
}
componentDidMount(){