首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React .getBoundingClientRect不工作

React .getBoundingClientRect不工作
EN

Stack Overflow用户
提问于 2019-09-20 10:45:40
回答 1查看 1.1K关注 0票数 0

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

通常,我只是尝试获取用户在画布上单击的点,而事件只返回相对于整个页面的绝对位置,因此我需要画布的位置(它是动态的)来减去该偏移量。有没有什么方法可以让我不用做.getBoundingClientRect()呢?

代码语言:javascript
复制
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"));
代码语言:javascript
复制
<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>

EN

回答 1

Stack Overflow用户

发布于 2019-09-20 11:00:51

代码语言:javascript
复制
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>
    );
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58021131

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档