如何确保 canvas 与 html 中的视频大小相同?

How to make sure canvas is of same size of video in html?

我在页面上显示了一个本地视频和一个远程视频。我在移动设备上使用此 html 页面。它工作正常。现在我必须使用鼠标在本地视频上绘制(并使用 canvas)。但我们没有指定视频元素的确切位置。所以无法思考如何在本地视频上准确呈现 canvas。以下是文件。

HTML:

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="/css/main.css" />
</head>

<body>
  <h1>Realtime communication with WebRTC</h1>

  <div id="videos">
    <video id="localVideo" autoplay muted></video>
    <video id="remoteVideo" autoplay></video>
  </div>

</body>
</html>

CSS:

body {
  font-family: sans-serif;
}

video {
  max-width: 100%;
  width: 320px;
}

任何人都可以让我知道如何将 canvas 完全覆盖在 localVideo 上。 Canvas 应该和 localVideo 在同一位置,并且应该和 localVideo 大小相同。

您可以使用 getBoundingClientRect() 方法获取有关当前元素位置的信息,然后使用此信息来定位 canvas 元素。

检查以下示例:

document.addEventListener("DOMContentLoaded", function(){
  const canvas = document.getElementById("canvasEl")
  const vid = document.getElementById("localVideo");
  const vidStyleData = vid.getBoundingClientRect();
  canvas.style.width = vidStyleData.width + "px";
  canvas.style.height = vidStyleData.height + "px";
  canvas.style.left = vidStyleData.left + "px";
  canvas.style.top = vidStyleData.top + "px";
});
body {
  font-family: sans-serif;
}

video {
  max-width: 100%;
  width: 320px;
}
canvas {
  position: absolute;
}
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="/css/main.css" />
</head>

<body>
  <h1>Realtime communication with WebRTC</h1>

  <div id="videos">
    <video id="localVideo" autoplay muted></video>
    <video id="remoteVideo" autoplay></video>
  </div>

<canvas id="canvasEl"></canvas>
</body>
</html>

Note that I set the position of the canvas to absolute using the css. If you want you can do this with javascript as well.

您可以使用getBoundingClientRect()方法计算<video>元素的X和Y位置,也可以同时使用offsetWidthoffsetHeight属性得到它的宽度和高度。

然后您应该将 position: absolute; 添加到 <canvas> 元素,以便您可以设置 topleft 属性的值。

这是您的代码(检查代码片段以查看区别!):

let xPos = window.scrollX + document.querySelector('#localVideo').getBoundingClientRect().left;
let yPos = window.scrollY + document.querySelector('#localVideo').getBoundingClientRect().top;

document.getElementById('_canvas').style.left = xPos + "px";
document.getElementById('_canvas').style.top = yPos + "px";

document.getElementById('_canvas').style.width = document.querySelector('#localVideo').offsetWidth + "px";
document.getElementById('_canvas').style.height = document.querySelector('#localVideo').offsetHeight + "px";
body {
  font-family: sans-serif;
}

video {
  max-width: 100%;
  width: 320px;
}

canvas {
  position: absolute;
}
<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <h1>Realtime communication with WebRTC</h1>

  <div id="videos">
    <video id="localVideo" autoplay muted></video>
    <video id="remoteVideo" autoplay></video>
  </div>

<canvas id="_canvas"></canvas>
</body>
</html>