画布Canvas转DataURL图像png质量不起作用

3
我一直在尝试将HTML5画布转换为低质量的dataUrl,因为我必须通过服务器传输数据URL文件,但无论我怎么做,最终都会得到高质量的图片。
dataURL = document.getElementById('canvas').toDataURL("image/png", 1);

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

质量不会改变,字符串长度保持不变,当我下载这张图片时,在两种情况下的质量都相同。你知道我做错了什么吗?

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>


该参数仅对有损压缩(如JPEG和WebP)有效。PNG是无损的,因此质量概念不适用。 - user5734311
在视觉质量/压缩方面,哪种格式更好? - Woold
JPG只适用于照片,对于任何类似于标志或带有文本的内容,您应该使用其他格式。 - user5734311
1个回答

6
因为PNG是一种无损格式。您无法调整质量,因为它始终为1。
来自规范
一个介于0和1之间的数字,表示用于使用有损压缩的图像格式(如image/jpeg和image/webp)的图像质量。

1
在视觉质量/压缩方面,哪种格式更好? - Woold
@支持有损压缩的文件格式包括image/jpeg和image/webp。 - Wessam El Mahdy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接