toDataURL / toBlob
Neben canvas.toDataUL ist canvas.toBlob eine weitere Methode, um die Zeichnung auf einem HTML-Canvas-Element festzuhalten und sie z.B. als PNG oder JPG zum Download anzubieten.
toBlob hat eine Callback-Funktion als Argument, die den frisch erzeugten Blob erzeugt. Weitere Argumente sind der Mime-Type (PNG oder JPG), und falls ein JPG erzeugt werden soll, die Qualitätsstufe des JPGs.
canvas.toBlob(callback); canvas.toBlob(callback, MIME type); canvas.toBlob(callback, MIME type, JPEG quality level); callback(Blob)
Per Vorgabe erzeugt toBlob ein PNG.
Beispiel: Bitmap und SVG als PNG
can.toBlob(function (blob) { const img = document.createElement ("img"); const url = URL.createObjectURL(blob); img.setAttribute("src", url); img.style = "width:100%;height:auto"; const link = document.createElement ("A"); link.download = "flieger.png"; const span = document.createElement("SPAN"); span.textContent = "DOWNLOAD (Format: " + blob.type + " Größe: " + blob.size + ")"; link.appendChild(span); link.style = "letter-spacing: 2px; font-weight:400"; link.href = URL.createObjectURL(blob); document.querySelector(body).appendChild(link); });