画布未在reactjs中呈现 [英] Canvas not rendering In reactjs

查看:64
本文介绍了画布未在reactjs中呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to add canvas on the website that i am developing but i can seem to understand why the canvas in not showing up. what could be the issue?

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

Below is what i have tried. When i hover the mouse on the header it shows that the canvas is updating but not showing anything on the screen

Canvas.jsx

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>
   )}
}

我要实现的是一个带有粒子的画布。悬停时,粒子应朝着光标所在的位置移动并缩放绿色粒子

what I want to achieve is a canvas with particles.on hover the particles should move towards where the cursor is headed and zoom the greener particles

推荐答案

您可以使用refs(请注意,在大多数情况下,facebook不鼓励使用refs,请参见文档

You could use refs (note that facebook discourages the uses of refs on most situations, see the documentation.

我会这样做:

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>  
  )}
}

这篇关于画布未在reactjs中呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆