-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathimage-to-canvas.ts
82 lines (73 loc) · 2.34 KB
/
image-to-canvas.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { createContext } from '../create-context'
import { IS_SAFARI, consoleTime, consoleTimeEnd, consoleWarn, loadMedia } from '../utils'
import type { Context } from '../context'
import type { Options } from '../options'
export async function imageToCanvas<T extends HTMLImageElement>(
image: T,
options?: Options,
): Promise<HTMLCanvasElement> {
const context = await createContext(image, options)
const {
requestImagesCount,
timeout,
drawImageInterval,
debug,
} = context
debug && consoleTime('image to canvas')
const loaded = await loadMedia(image, { timeout })
const { canvas, context2d } = createCanvas(image.ownerDocument, context)
const drawImage = () => {
try {
context2d?.drawImage(loaded, 0, 0, canvas.width, canvas.height)
} catch (error) {
consoleWarn('Failed to drawImage', error)
}
}
drawImage()
// fix: image not decode when drawImage svg+xml in safari/webkit
if (IS_SAFARI) {
for (let i = 0; i < requestImagesCount; i++) {
await new Promise<void>(resolve => {
setTimeout(() => {
drawImage()
resolve()
}, i + drawImageInterval)
})
}
}
debug && consoleTimeEnd('image to canvas')
return canvas
}
function createCanvas(ownerDocument: Document, context: Context) {
const { width, height, scale, backgroundColor, maximumCanvasSize: max } = context
const canvas = ownerDocument.createElement('canvas')
canvas.width = Math.floor(width * scale)
canvas.height = Math.floor(height * scale)
canvas.style.width = `${ width }px`
canvas.style.height = `${ height }px`
if (max) {
if (canvas.width > max || canvas.height > max) {
if (canvas.width > max && canvas.height > max) {
if (canvas.width > canvas.height) {
canvas.height *= max / canvas.width
canvas.width = max
} else {
canvas.width *= max / canvas.height
canvas.height = max
}
} else if (canvas.width > max) {
canvas.height *= max / canvas.width
canvas.width = max
} else {
canvas.width *= max / canvas.height
canvas.height = max
}
}
}
const context2d = canvas.getContext('2d')
if (context2d && backgroundColor) {
context2d.fillStyle = backgroundColor
context2d.fillRect(0, 0, canvas.width, canvas.height)
}
return { canvas, context2d }
}