javascript canvas capture screenshot of camera issue in Samsung Browser

465 views Asked by At

Well, I'm having a very weird issue that's only happening on Samsung Browser. On Chrome and other browsers, this works well.

When I take a snapshot of a current frame of a video (Currently the mobile camera) on javascript I get the image with distortion and generally bad.

Bad snapshot from video camera

The code that takes the snapshot is:

   function takeSnapshot() {
        // Here we're using a trick that involves a hidden canvas element.  
        video.pause();
        var hidden_canvas = document.createElement('canvas'),
            context = hidden_canvas.getContext('2d');
    
        var width = video.videoWidth,
            height = video.videoHeight;
    
        if (width && height) {
    
            // Setup a canvas with the same dimensions as the video.
            hidden_canvas.width = width;
            hidden_canvas.height = height;
    
            // Make a copy of the current frame in the video on the canvas.
            context.drawImage(video, 0, 0, width, height);
    
            // Turn the canvas image into a dataURL that can be used as a src for our photo.
            return hidden_canvas.toDataURL('image/jpeg');
        }
    }

Do I'm missing something else to make it work in Samsung Browser? Or I just put a message that this is not compatible with this browser? Currently tested on Samsung Galaxy S9, Android 10.

------------- Update

I found what is causing the image to be captured badly. I'm using custom size for the image, in this case, is a horizontal rectangle. I do this when init the video:

var w = 2000; // This renders the video as a horizontal rectangle, this does the issue.
var h = 1200;     

var userAgent = (typeof navigator !== 'undefined' && navigator.userAgent) || '';
var isSamsungBrowser = userAgent.indexOf('SamsungBrowser') >= 0;

// Quick fix:
if(SamsungBrowser){ // If I render as vertical renctangle, the issue is gone.
    w = 1200;
    h = 2000;
}

navigator.getMedia(
        {
          video:
           {
            deviceId: videoSource ? { exact: videoSource } : undefined,
            width: { ideal: h }, 
            height: { ideal: w }
           }
         },
         // Success Callback
         function (stream) {
          // Create an object URL for the video stream and
          // set it as src of our HTLM video element.
          try {
             currentStream = stream;
             video.srcObject = stream;
             } catch (error) {
                video.src = window.URL.createObjectURL(stream);
             }
           window.stream = stream;
            // Play the video element to start the stream.
           video.play();
            video.onplay = function () {
                 showVideo();
            };
         }

vertical video

0

There are 0 answers