简体   繁体   中英

How can I get the position of an HTML element when the browser window is resized?

I have a function that draw a CANVAS line and make its get the same coordinates of a <div> by using offsetLeft. The line searchs the same position of the <div> making its get glued on the <div> It is working good BUT ONLY when the page loads and the browser refreshs.

drawCanvas() {
  const c = document.getElementById("canvas");
  const lineH = c.getContext("2d");      
  c.width = window.innerWidth;
  c.height = window.innerHeight;
  const lineV = c.getContext("2d");   

 const positionCanvas = () => {
   lineV.clearRect(0, 0, c.width, c.height);    
   const divPosition = document.querySelector('.myDiv').offsetLeft  
   lineV.fillStyle = "grey";
   lineV.fillRect(divPosition , 0, 2, window.innerHeight);
   lineV.fill();
}

  positionCanvas() 

  window.onresize = () => {    
  lineV.height = window.innerHeight; 
  positionCanvas()     
}  

I would like to make it work good everytime even and especially when I'm handling the resizing of the window. How can I solve it?

Example:

  1. The page is loaded: OK!!! The canvas line is glued on <div>

  2. While the user is manually resizing the window's browser: NOT WORKING!!! The canvas search the <div> but not get glued on its, there is a distance between both.

  3. After the stop of the browser resizing: NOT WORKING!!! the lline still separated from the <div>

  4. Refresh the browser in a new position: OK!!! canvas line is glued on <div>

I found the solution. Just put the function drawCanvas() into the window.onresize rather the positionCanvas() .

Just like that:

 window.onresize = () => {  
  drawCanvas()    
}   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM