Search code examples
htmlcanvasbase64data-uri

Detect browser support for image type in canvas.toDataURL


I am trying to get dataUrl from <canvas> element using canvas.toDataURL(). By default, it returns image/png, but some browsers support the image/jpeg filetype.

How can i detect if a browser supports image/jpeg?


Solution

  • You just specify that you want JPEG like this:

    var quality = 0.8;
    var dataUri = canvas.toDataURL('image/jpeg', quality); // quality is optional
    

    If your dataUri now contains the same string JPEG is supported. Otherwise the string will be image/png.

    if (dataUri.match('image/jpeg')) {
        // support jpeg
    }
    

    That being said, I don't think there is any browser which do not support the jpeg format. A test like this is better suited for more uncommon formats in various degrees such as webp, bitmap etc.

    For a general test you could do:

    function hasSupport(mime) {
        var canvas = document.createElement('canvas');
        canvas.width = canvas.height = 1;
        var uri = canvas.toDataURL(mime);
        return (uri.match(mime) !== null);
    }