我是html5 canvas的新手。我试图在画布上做一个盒子。我想要此框内有一条垂直线(高度等于框高)。我希望这条线沿水平方向移动,例如在“暂停并播放”按钮上说。我做不到。有人可以帮我吗?

我编写了在框内形成一条垂直线的代码。

class App extends Component {

    componentDidMount(){
        canvas = document.getElementsByTagName("canvas")[0];
        ctx = canvas.getContext("2d");

        ctx.beginPath();

        ctx.moveTo(0,0);

        ctx.lineTo(0,200);

        ctx.stroke();

        ctx.fillStyle = "#808891";
    }


  render() {
    return (
      <div className="App">

          <canvas id="DemoCanvas" width="500" height="200"></canvas>
      </div>
    );
  }
}


但是我不知道如何使这条线沿水平方向移动(将其视为视频时间轴的标记)

最佳答案

您需要创建一个函数,该函数将首先清除先前绘制的线条,然后在特定的X位置绘制新的线条。

然后,每次需要时使用新的X位置调用此函数,例如,使用requestAnimationFrame。

这是一个带有播放/暂停按钮示例的代码段。



var left = 0;

const btn = document.getElementById("btn");
canvas = document.getElementsByTagName("canvas")[0];
ctx = canvas.getContext("2d");
const w = canvas.width;
const h = canvas.height;

let xPos = 0;
let playing = false;

function updateVert() {
  if(!playing) {
    cancelAnimationFrame(updateVert);
    return;
  }

  xPos += 1;

  if(xPos >= w) {
    // stop animation...
    xPos = 0;
    playing = false;
    btn.value = "Play";
  }

  // reset rectangle content to erase previous line...
  ctx.clearRect(0, 0, w, h);

  // draw new one...
  ctx.beginPath();
  ctx.strokeStyle = "#19f";
  ctx.lineWidth = 2;
  ctx.moveTo(xPos, 0);
  ctx.lineTo(xPos, 200);
  ctx.stroke();

  if(playing) requestAnimationFrame(updateVert);
}

document.getElementById("btn").addEventListener('click', function(e) {
  e.preventDefault();

  if(playing) {
    // pause...
    playing = false;
  }
  else {
    playing = !playing;
    updateVert();
  }

  btn.value = playing?"Pause":"Play";
});

canvas {
  border: 1px solid silver;
}

<div className="App">
  <canvas id="DemoCanvas" width="200" height="80"></canvas>
</div>
<input type="button" id="btn" value="Play">

10-07 14:03