Skip to content

Instantly share code, notes, and snippets.

@uupaa
Last active April 11, 2021 13:37
Show Gist options
  • Save uupaa/6410357 to your computer and use it in GitHub Desktop.
Save uupaa/6410357 to your computer and use it in GitHub Desktop.
canvas.toDataURL("image/webp");
<canvas id="canvas"></canvas>
<script>
var ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 8, 8);

var webp = canvas.toDataURL("image/webp"); // Chrome only?
var png  = canvas.toDataURL("image/png");
var jpg  = canvas.toDataURL("image/jpeg");

console.log(webp.length, webp); //  263 byte
console.log(png.length, png);   // 1918 byte
console.log(jpg.length, jpg);   // 1938 byte

document.body.appendChild(new Image).src = webp;
document.body.appendChild(new Image).src = png;
document.body.appendChild(new Image).src = jpg;
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment