Canvas 到 dataURL 图片 Png 质量不工作

Canvas to dataURL Image Png quality not working

我一直在尝试将 HTML5 canvas 转换为低质量的 dataUrl,因为我必须通过服务器传输 dataURL 文件,但我是否这样做

dataURL = document.getElementById('canvas').toDataURL("image/png", 1);

dataURL = document.getElementById('canvas').toDataURL("image/png", 0.00001);

质量没有改变,字符串长度保持不变,当我在两种情况下下载回该图像时其质量相同,知道我做错了什么吗?

这是一个例子,但是 canvas 我正在做的这个有更好的 pixelRatio 并且非常详细

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>

因为PNG是无损格式。您无法调整质量,因为它始终为 1。

来自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.