如何在窗口调整大小时停止乘以画布线?

时间:2018-04-26 10:21:13

标签: javascript canvas

我有一个绘制CANVAS线的函数,并使用<div>使其获得offsetLeft的相同坐标,并将其搜索移动到<div>的相同位置。它运作良好。

 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()     
}  

问题是我不知道如何避免在调整窗口大小时重复多次行的默认CANVAS行为。我该如何解决?谢谢

1 个答案:

答案 0 :(得分:0)

答案是:

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