Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am displaying one local video and one remote video on the page. I am using this html page on the mobile. It is working fine. Now I have to draw on the local video using mouse (and using canvas). But we didn't specify the exact location of video elements. So unable to think how to render the canvas exactly over local video. Below are the files.

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;
}

Can any one please let me know how to overlay canvas exactly over localVideo. Canvas should be at the same position of localVideo and should be same size of localVideo.

like image 257
kadina Avatar asked Oct 16 '25 04:10

kadina


1 Answers

You can use the getBoundingClientRect() method to get the information about the position of the current element, and then use this information in order to position the canvas element.

Check the following example:

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.

like image 178
Dekel Avatar answered Oct 17 '25 19:10

Dekel