0

I have a function that draw a CANVAS line and make this get the same coordinates of a <div> by using offsetLeft and move its searching the same position of the <div>. It is working good.

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

const positionCanvas = () => {
 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()     
}  

The problem is I don't know how avoid the default CANVAS behavior that duplicates many times the line when I resize the windows. How do I solve it? Thank you

claudiopb
  • 1,056
  • 1
  • 13
  • 25

1 Answers1

0

The answer is:

  const positionCanvas = () => {
    lineV.clearRect(0, 0, c.width, c.height); //<-- new line added in the code
    //... rest of the code ommited
claudiopb
  • 1,056
  • 1
  • 13
  • 25