phoboslab / jsmpeg

MPEG1 Video Decoder in JavaScript
MIT License
6.35k stars 1.43k forks source link

Capture an image from canvas #355

Open Mactacs opened 4 years ago

Mactacs commented 4 years ago

Hi. I have a problem with capturing image in canvas. I used this method below but my problem is that it causes an error (Cannot read property toDataURL is undefined). I don't know what is wrong because my player works fine.

<script type = "text/javascript"> var canvas = document.getElementById('video'); var ws = new WebSocket("ws://10.108.1.18:9999") var url = "ws://10.108.1.18:9999"; var player = new JSMpeg.Player(url, {canvas: canvas, autoplay:true,audio:false,loop: true}); function captureFix(){ var img = document.createElement('img'); img.src = player.canvas.toDataURL('image/webp', 0.7) var capImage = document.getElementById("capImage"); capImage.src = img.src; } </script>

fossephate commented 4 years ago

The preserveDrawingBuffer option has to be enabled for canvas.toDataURL() to work https://github.com/phoboslab/jsmpeg/blob/master/README.md#usage

Mactacs commented 4 years ago

Like this one? I tried below but the error still persists

<script type = "text/javascript"> var canvas = document.getElementById('video'); var ws = new WebSocket("ws://10.108.1.18:9999") var url = "ws://10.108.1.18:9999"; var player = new JSMpeg.Player(url, {canvas: canvas, autoplay:true,audio:false,loop: true,preserveDrawingBuffer: true}); function captureFix(){ var img = document.createElement('img'); img.src = player.canvas.toDataURL('image/webp', 0.7) var capImage = document.getElementById("capImage"); capImage.src = img.src; } </script>

phoboslab commented 4 years ago

There is no player.canvas property anymore. You can access the canvas element through player.renderer.canvas, though this is undocumented and may change.

The preferred way to do this is to use your own reference to the canvas element. Since you do var canvas = document.getElementById('video'); (and later hand that canvas over to jsmpeg) you can just call img.src = canvas.toDataURL('image/webp', 0.7).