我一直在尝试将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>