Javascript Canvas toBlob

Canvas als Bild laden

canvas.toBlob erweitert die Techniken zum Umwandeln der Zeichnung im Canvas. Ein Blob kann als URL für ein a-Element oder als src-Attribut eines img-Tags eingesetzt werden und die Daten können dem Benutzer zum Download angeboten werden.

23-02-02 SITEMAP CSS HTML JS Basis JS Web Tutorial SVG

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 setzt als Argument eine Callback-Funktion, die den 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.

Der Unterschied zwischen toBlob und toDataURL(): toDataURL ist synchron und blockiert die Benutzerschnittstelle (ähnlich wie ganz ganz früher der synchrone XHR), während toBlob die eigentliche Konvertierung in ein Bild asynchron durchführt. Die Erzeugung des Bilddatei aus einem Canvas To generate an image file from a canvas is a slow operation, you need to export all the pixel data, un-multiply it, and then call the compression algorithms.

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);
});