How to display m3u8 video to canvas in safari?

by mallory_cormier , in category: Javascript , a month ago

How to display m3u8 video to canvas in safari?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , a month ago

@mallory_cormier 

To display an m3u8 video file to a canvas element in Safari, you can use the following steps:

  1. Create a video element in your HTML document:
1
2
3
<video id="videoElement" controls>
  <source src="path/to/your/video.m3u8" type="application/x-mpegURL">
</video>


  1. Create a canvas element in your HTML document where you want to display the video:
1
<canvas id="canvasElement" width="640" height="360"></canvas>


  1. Use JavaScript to capture frames from the video and draw them onto the canvas element:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
var video = document.getElementById('videoElement');
var canvas = document.getElementById('canvasElement');
var ctx = canvas.getContext('2d');

video.addEventListener('play', function(){
  var $this = this;
  (function loop() {
    if (!$this.paused && !$this.ended) {
      ctx.drawImage($this, 0, 0, canvas.width, canvas.height);
      setTimeout(loop, 1000 / 30); // Adjust the framerate here
    }
  })();
}, 0);


  1. Play the video:
1
video.play();


This code will continuously capture frames from the video and draw them onto the canvas at a specified framerate. Note that playing video in Safari might require user interaction, so make sure to trigger the video playback in response to a user action.


Please note that playing HLS (m3u8) files directly on a canvas might not work in some browsers due to security restrictions. It's recommended to use a video element for playing such files.