Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I overlay a canvas over a video

Tags:

html

css

canvas

I have a video and a canvas inside a div and I want to overlay the canvas over the video. I tried this:

.container {
  margin: 0 auto;
  position: relative;
}

.video {
  width: 100%;
  height: auto;
  position: absolute;
  top: 0;
  left: 0;
}

.canvas {
  width: 100%;
  height: auto;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
}

JSFiddle here

But for some reason the canvas does not cover the whole video, it is shorter. How do I fix that?

like image 366
Priyatham Avatar asked Sep 24 '16 01:09

Priyatham


2 Answers

Canvas must have absolute width and height. When the video load you can assign the right width and height.

Here: jsfiddle: https://jsfiddle.net/7sk5k4gp/13/

PS: I put a red filter for better understanding.

Code above:

<style>
  .canvas {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
  background-color:rgba(255,0,0,0.5);
}

</style>
<div class="container">
  <video class="video" id="vd1" controls autoPlay      src="http://upload.wikimedia.org/wikipedia/commons/7/79/Big_Buck_Bunny_sma    ll.ogv" onplay="resize_canvas(this)"></video>
  <canvas class="canvas" id="cv1"></canvas>
</div>
<script>

function resize_canvas(element)
{
  var w = element.offsetWidth;
  var h = element.offsetHeight;
  var cv = document.getElementById("cv1");
  cv.width = w;
  cv.height =h;
}
</script>
like image 189
danielarend Avatar answered Sep 16 '22 18:09

danielarend


Adjusting the canvas's height to 100% makes sure the entire video is covered. The auto tag just adjusts the size of an object relative to the amount of data needed to be shown. E.g. for a <\p> tag with 'width:auto' the more text, the wider the tag etc. .container { margin: 0 auto; position: relative; }

.video {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
}

.canvas {
  width: 100%;
  height: 100%;
  position: fixed;
  background-color:black;
  top: 0;
  left: 0;
  z-index: 10;
}
like image 29
UnknownRobotik Avatar answered Sep 18 '22 18:09

UnknownRobotik