Problem with HTMLCanvasElement.toBlob(), "image/webp", & anchor (<a>) using download attribute
I have a local HTML/Javascript document I use for compressing local image files. It relies on HTMLCanvasElement.toBlob() to achieve the compression in the usual way; a p… (read more)
I have a local HTML/Javascript document I use for compressing local image files. It relies on HTMLCanvasElement.toBlob() to achieve the compression in the usual way; a pertinent excerpt:
const output = document.getElementById("outputDiv"); const blobURL = URL.createObjectURL(file); const img = new Image(); img.src = blobURL; // ... img.onload = function () { URL.revokeObjectURL(this.src); const canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height; const ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, img.width, img.height); canvas.toBlob( (blob) => { const anchor = document.createElement("a"); anchor.download = getNewFileName(file.name); /* uses extension .webm for .webm, .jpg for everything else */ anchor.href = URL.createObjectURL(blob); anchor.textContent = "DOWNLOAD"; output.append(anchor); }, mime, /* set earlier based on file extension: .webm -> "image/webm", everything else -> "image/jpeg" quality / 100 /* (user-specified) */ ); };
Here's the quirky thing, though: when I'm compressing, say, a .jpeg file (or a .png), clicking on the download link opens a save-file dialog, but when using a .webm file, it opens the compressed image in a new tab! True, I can always then save the image from there (the resulting file is in Firefox's temp folder), but I don't understand the difference in behavior -- and indeed, in at least one other browser I tried (the latest Vivaldi) the download happens as expected regardless of input file type. In all cases the anchor hrefs look like, e.g., "blob:null/724ab85e-53ba-4890-9868-7f1ba27d4278".
Any idea why this is happening? I highly doubt it's the intended behavior.
Browser: Firefox 132.0.2 for Windows. Environment: Windows 10 Home 22H2 version 10.0.19045.