等待 Javascript 重绘

Bra*_*sen 4 html javascript css

我试图在更改元素的背景后运行一些代码。我想在背景发生视觉变化后运行代码改变后运行代码,而不仅仅是在内部改变。所以我想等待重画。我尝试使用 rAF 执行此操作,但这似乎不是正确的方法,因为代码在背景颜色发生视觉更改之前执行(尽管谈论的是毫秒)。

我尝试使用以下代码来实现我的目标(没有运气):

  requestAnimationFrame(() => {
    document.getElementsByTagName("body")[0].style.backgroundColor =
      "rgb(0, 75, 75)";
      requestAnimationFrame(() => {
        socket.emit("notify-black");
      });
  });
Run Code Online (Sandbox Code Playgroud)

等待重画的正确方法是什么?

Cer*_*nce 6

requestAnimationFrame将在下一次重绘之前运行回调。将要运行的代码放入setTimeout,因为超时回调将在重绘完成后几乎立即运行。

您还可以使用document.body代替document.getElementsByTagName("body")[0]

requestAnimationFrame(() => {
  document.body.style.backgroundColor = "rgb(0, 75, 75)";
  requestAnimationFrame(() => {
    setTimeout(() => {
      socket.emit("notify-black");
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

现场演示,使用alert(which block) 而不是socket.emit

requestAnimationFrame(() => {
  document.body.style.backgroundColor = "rgb(0, 75, 75)";
  requestAnimationFrame(() => {
    setTimeout(() => {
      socket.emit("notify-black");
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

另一个使用 html2canvas 截取屏幕截图的示例代码。打开example.com,打开控制台,然后运行以下命令:

const script = document.body.appendChild(document.createElement('script'));
script.src = 'https://html2canvas.hertzen.com/dist/html2canvas.js'
script.onload = () => {
  requestAnimationFrame(() => {
    document.body.style.backgroundColor = "rgb(0, 75, 75)";
    requestAnimationFrame(() => {
      setTimeout(() => {
        html2canvas(document.querySelector("body")).then(canvas => {
          document.write('<img src="'+canvas.toDataURL("image/png")+'"/>');
        });
      });
    });
  });
};
Run Code Online (Sandbox Code Playgroud)