I've been trying to convert an HTML5 canvas to dataUrl with a low quality because I have to transfer the dataURL files through a server but wether I do
dataURL = document.getElementById('canvas').toDataURL("image/png", 1);
or
dataURL = document.getElementById('canvas').toDataURL("image/png", 0.00001);
the quality doesn't change, the string length stay the same and when I download back that image in both cases its the same quality, any idea what I am doing wrong?
this is an example but the canvas I am doing this has a much better pixelRatio and is well detailled
const canvas = document.querySelector('canvas')
const button = document.querySelector('button')
const ctx = canvas.getContext('2d')
canvas.width = window.innerWidth
canvas.height = window.innerHeight
ctx.fillStyle = 'red'
ctx.fillRect(50, 50, 100, 100)
ctx.fillStyle = 'green'
ctx.fillRect(60, 60, 80, 80)
ctx.fillStyle = 'white'
ctx.font = "bold 20px sans-serif"
ctx.fillText("What a square!", 0, 90)
document.getElementById("b1").addEventListener('click', () => {
let data = canvas.toDataURL("image/png",0.000001);
downloadImage(data, "low.png");
})
document.getElementById("b2").addEventListener('click', () => {
let data = canvas.toDataURL("image/png",1.0);
downloadImage(data, "high.png");
})
function downloadImage(data, filename = 'untitled.png') {
const a = document.createElement('a');
a.href = data;
a.download = filename;
document.body.appendChild(a);
a.click();
}
<button id="b1">Save Low</button>
<button id="b2">Save High</button>
<canvas></canvas>
It's because PNG is a lossless format. You can't tune the quality because it is always 1.
From the spec :
A Number between 0 and 1 indicating the image quality to use for image formats that use lossy compression such as image/jpeg and image/webp.