【问题标题】:Canvas to dataURL Image Png quality not working画布 todataURL 图像 Png 质量不起作用
【发布时间】:2020-09-27 13:12:13
【问题描述】:

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

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

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

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

这是一个示例,但我正在做的画布具有更好的像素比,并且细节处理得很好

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 是无损的,因此质量的概念不适用。
  • 哪种格式在视觉质量/压缩方面更好?
  • jpg 只适用于照片,对于任何类似标志或具有特色的文字,你应该使用其他东西。

标签: javascript canvas png todataurl pixel-ratio


【解决方案1】:

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

来自spec

一个介于 0 和 1 之间的数字,指示用于图像的图像质量 使用有损压缩的格式,例如 image/jpeg 和 image/webp。

【讨论】:

  • 哪种格式在视觉质量/压缩方面更好?
  • 不客气。如果我的回答是正确的,请不要忘记将其标记为已接受。这是一个不同的问题,但当然 Webp 比 Jpg 好得多(因为它比 Jpg 更新了 20 多年......)但是,Safari 和 Apple 设备通常不支持它(因为它是由 Google 开发的,而 Apple 不支持) '不像谷歌),所以你必须在苹果设备上回退到 Jpg。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-18
  • 2013-11-11
  • 1970-01-01
  • 2012-10-08
  • 2014-04-12
  • 2015-01-03
  • 1970-01-01
相关资源
最近更新 更多