jsmpeg icon indicating copy to clipboard operation
jsmpeg copied to clipboard

Capture an image from canvas

Open Mactacs opened this issue 5 years ago • 3 comments

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>

Mactacs avatar Sep 02 '20 00:09 Mactacs

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

fossephate avatar Sep 02 '20 00:09 fossephate

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>

Mactacs avatar Sep 02 '20 00:09 Mactacs

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).

phoboslab avatar Sep 02 '20 08:09 phoboslab