反应.getBoundingClientRect不起作用

时间:2019-09-20 02:45:40

标签: reactjs html5-canvas

我正在尝试使用.getBoundingClientRect()来获取当前画布在React中的位置。但是它一直返回DOMRect {x: 0, y: 0, width: 0, height: 0, top: 0, …},但是我的画布不在页面的左上角。有什么想法吗?

通常,我只是想让用户点击画布,而该事件仅返回相对于整个页面的绝对位置,因此我需要画布的位置(它是动态的)减去该偏移量。不用.getBoundingClientRect()我有什么办法可以解决的吗?

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.canvasRef = React.createRef();
  }

  componentDidMount() {
    const c = this.canvasRef.current;
    console.log(c);
    setInterval(console.log(c.getBoundingClientRect()), 1);
  }

  render() {
    return (
      <React.Fragment>
        <div
          className=""
          style={{
            width: "288px",
            height: "188px",
            position: "relative"
          }}
        >
          <canvas
            ref={this.canvasRef}
            style={{
              position: "absolute",
              width: "263px",
              height: "168px",
              top: "10px",
              left: "10px",
              backgroundColor: "#DCDEE0"
            }}
            onClick={e => {
              e.persist();
              console.log(e);
            }}
          ></canvas>
        </div>
      </React.Fragment>
    );
  }
}

ReactDOM.render(<Example />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

1 个答案:

答案 0 :(得分:0)

class Canvas extends React.Component {
  constructor(props) {
    super(props);
    this.canvasRef = React.createRef();
  }

  componentDidMount() {
    const c = this.canvasRef.current;
    console.log(c);
   setInterval(console.log(c.getBoundingClientRect()), 1);
  }

  onClick = e => {
    const { pageX, pageY } = e;

    console.log(pageX, pageY);
  };

  render() {
    return (
      <React.Fragment>
        <div
          className=""
          style={{
            width: "288px",
            height: "188px",
            position: "relative"
          }}
        >
          <canvas
            ref={this.canvasRef}
            style={{
              position: "absolute",
              width: "263px",
              height: "168px",
              top: "10px",
              left: "10px",
              backgroundColor: "#DCDEE0"
            }}
            onClick={this.onClick}
          />
        </div>
      </React.Fragment>
    );
  }
}