How to set the image quality while converting a canvas with the "toDataURL" method?

79,287

Solution 1

The second argument of the function is the quality. It ranges from 0.0 to 1.0

canvas.toDataURL(type,quality);

Here you have extended information

And I don't think it's possible to know the quality of the image once is converted. As you can see on this feedle the only information you get when printing the value on the console is the type and the image code itself.

Here's a snippet of code I made to know the default value of the quality used by the browser.

    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
    ctx.fillStyle="#FF0000";
    ctx.fillRect(0,0,150,75);

    var url = c.toDataURL('image/jpeg');
    var v = 0
    for(var i = 0; i < 100; i++ ){

        v += 0.01;
        x = parseFloat((v).toFixed(2))
        var test = c.toDataURL('image/jpeg', x);

        if(test == url){
            console.log('The default value is: ' + x);
        }
    }

Basically I thought that the change on the image itself would be reflected on the base64 string. So the code just try all the possible values on the toDataURL() method and compares the resulting string with the default one. And it seems to work. For chromium I get 0.92.

Here is the working example on a fiddle.

Solution 2

Using Fabric.js, a very simple and human-readable way, is this:

canvas.toDataURL({
   format: 'jpeg',
   quality: 0.8
});

This also allows you to have other options, giving you the ability to crop the image, etc:

canvas.toDataURL({
    format: 'png',
    left: 300,
    top: 250,
    width: 200,
    height: 150
})

jsFiddle: http://jsfiddle.net/7f9bqs00/30/

Share:
79,287

Related videos on Youtube

jedierikb
Author by

jedierikb

OB1 Kenobi was the result of an Off-By-One [OB1] error in the clone wars.

Updated on July 09, 2022

Comments

  • jedierikb
    jedierikb almost 2 years

    I want to set the quality factor when I encode a canvas element to jpg.

    var data = myCanvas.toDataURL( "image/jpeg" );
    

    It does not give me a quality option. Is there an alternative library I can use?

    Related: what is the default quality setting used by the different browsers?

  • Thom Wiggers
    Thom Wiggers over 10 years
    The default value on firefox also is 0.92
  • Efran Cobisi
    Efran Cobisi over 10 years
    0.92 on Chrome 32 too.
  • Pat Mächler
    Pat Mächler about 6 years
    I want to update the url to the example to jsfiddle.net/7f9bqs00/30 . The original jsFiddle example url is jsfiddle.net/fabricjs/NfZVb. I updated the CDN lib, made the export examples more descriptive & meaningful. Furtermore I added buttons for interactivity.