Search code examples
javascripthtml5-canvasfabricjs

Add FabricJS Canva on top of a video


I want to add a FabricJS canvas on top of a video but I am unable to set the canvas position property to "absolute".

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.5.0/fabric.min.js"></script>
<div id="videoKit">
  <video id="video" controls preload="metadata">
    <source
      src="https://media.istockphoto.com/id/1760658147/fr/vid%C3%A9o/prise-de-vue-par-drone-de-dauphins-nageant.mp4?s=mp4-640x640-is&k=20&c=y9709pLK1KmLp1FZRzkKd8Pmx4xurbRqAK6RWKLSapc="
      type="video/mp4"/>
  </video>
  <canvas id="canvas"></canvas>
</div>

<script>
  var canvas = new fabric.Canvas('canvas', {
    width: 500,
    height: 500
  });

  var canvasNode = canvas.getElement();

  canvasNode.style.position = 'absolute';
  canvasNode.style.left = '0px';
  canvasNode.style.top = '0px';
  canvasNode.style.border = '2px solid #000';
</script>

I tried to change the CSS property of the initial canvas, upper canvas and lower-canvas as well as the canvas-container of the FabricJS set-up. But my canvas is still under the video.

Can we properly put a FabricJS canva on top of a video ?


Solution

  • After many attempts, I finally found out that the cause of this problem was in css.

    If you want to position the canvas tag as you wish, you must set the position property of the parent tag to "relative" and the video tag to "absolute".

    Here is my modified code based on your code. (2 lines have been changed.)

    <div id="app"></div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.5.0/fabric.min.js"></script>
    <div id="videoKit" style="position: relative">
      <video id="video" controls preload="metadata" style="position: absolute">
        <source
          src="https://media.istockphoto.com/id/1760658147/fr/vid%C3%A9o/prise-de-vue-par-drone-de-dauphins-nageant.mp4?s=mp4-640x640-is&k=20&c=y9709pLK1KmLp1FZRzkKd8Pmx4xurbRqAK6RWKLSapc="
          type="video/mp4"
        />
      </video>
      <canvas id="canvas"></canvas>
    </div>
    
    <script>
      var canvas = new fabric.Canvas('canvas', {
        width: 500,
        height: 500,
      });
    
      var canvasNode = canvas.getElement();
    
      canvasNode.style.position = 'absolute';
      canvasNode.style.left = '0px';
      canvasNode.style.top = '0px';
      canvasNode.style.border = '2px solid #000';
    </script>

    After testing it in my computer environment, I confirmed that it was operating normally.