我正在尝试使用.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>
发布于 2019-09-20 11:00:51
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>
);
}
}https://stackoverflow.com/questions/58021131
复制相似问题