Skip to content

Commit

Permalink
feat(dl-asset): add downloadCanvas()
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Nov 10, 2021
1 parent e3c490c commit ca657d4
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
3 changes: 3 additions & 0 deletions packages/dl-asset/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@
"./api": {
"import": "./api.js"
},
"./canvas": {
"import": "./canvas.js"
},
"./download": {
"import": "./download.js"
},
Expand Down
28 changes: 28 additions & 0 deletions packages/dl-asset/src/canvas.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { downloadWithMime } from "./raw.js";

/**
* Triggers canvas-to-blob conversion for given file type (and opt. `quality`),
* then triggers download via {@link downloadWithMime}. Default file type is
* `png`. Default quality is 0.95 (only used for JPEG/WebP).
*
* @param canvas
* @param baseName
* @param type
* @param quality
*/
export const downloadCanvas = (
canvas: HTMLCanvasElement,
baseName: string,
type: "png" | "jpeg" | "webp" = "png",
quality = 0.95
) => {
const mime = `image/${type}`;
canvas.toBlob(
(blob) =>
blob
? downloadWithMime(`${baseName}.${type}`, blob, { mime })
: console.warn("can't download canvas"),
mime,
quality
);
};
1 change: 1 addition & 0 deletions packages/dl-asset/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from "./api.js";
export * from "./canvas.js";
export * from "./download.js";
export * from "./raw.js";

0 comments on commit ca657d4

Please sign in to comment.