Skip to content

Commit

Permalink
Add type option to save canvas.toBlob as web or jpeg... (#205)
Browse files Browse the repository at this point in the history
* Add type option to save canvas.toBlob as web or jpeg

* Add documentation of type option
  • Loading branch information
june07 authored Nov 1, 2021
1 parent 5b35e82 commit 5aa3689
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 4 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,12 @@ You may experience loss of parts of the image if set to `true` and you are expor

Defaults to `false`

### type

A string indicating the image format. The default type is image/png; that type is also used if the given type isn't supported.
When supplied, the toCanvas function will return a blob matching the given image type and quality.

Defaults to `image/png`

## Browsers

Expand Down
4 changes: 4 additions & 0 deletions src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,8 @@ export interface Options {
* A boolean to turn off auto scaling for truly massive images..
*/
skipAutoScale?: boolean
/**
* A string indicating the image format. The default type is image/png; that type is also used if the given type isn't supported.
*/
type?: string
}
30 changes: 26 additions & 4 deletions src/util.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { Options } from './options'

const WOFF = 'application/font-woff'
const JPEG = 'image/jpeg'
const mimes: { [key: string]: string } = {
Expand Down Expand Up @@ -138,21 +140,41 @@ export function getPixelRatio() {
return ratio || window.devicePixelRatio || 1
}

export function canvasToBlob(canvas: HTMLCanvasElement): Promise<Blob | null> {
export function canvasToBlob(
canvas: HTMLCanvasElement,
options: Options = {},
): Promise<Blob | null> {
if (canvas.toBlob) {
return new Promise((resolve) => canvas.toBlob(resolve))
return new Promise((resolve) =>
canvas.toBlob(
resolve,
options.type ? options.type : 'image/png',
options.quality ? options.quality : 1,
),
)
}

return new Promise((resolve) => {
const binaryString = window.atob(canvas.toDataURL().split(',')[1])
const binaryString = window.atob(
canvas
.toDataURL(
options.type ? options.type : undefined,
options.quality ? options.quality : undefined,
)
.split(',')[1],
)
const len = binaryString.length
const binaryArray = new Uint8Array(len)

for (let i = 0; i < len; i += 1) {
binaryArray[i] = binaryString.charCodeAt(i)
}

resolve(new Blob([binaryArray], { type: 'image/png' }))
resolve(
new Blob([binaryArray], {
type: options.type ? options.type : 'image/png',
}),
)
})
}

Expand Down

0 comments on commit 5aa3689

Please sign in to comment.