-
Notifications
You must be signed in to change notification settings - Fork 0
/
document.js
86 lines (75 loc) · 2.04 KB
/
document.js
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
83
84
85
86
import { validHTML } from "./include.js"
//#region Types
/** @typedef {HTMLElement | HTMLDivElement | Element} targetElement */
//#endregion
const $d = document
/**
* @param {string} source
* @param {targetElement} primary
*/
export function search(source, primary = $d) {
return validHTML(primary).querySelector(source)
}
/**
* @param {string} source
* @param {targetElement} primary
*/
search.id = (source, primary = $d) => (
validHTML(primary).getElementById(source)
)
/**
* @param {string} source
* @param {targetElement} primary
*/
search.all = (source, primary = $d) => (
validHTML(primary).querySelectorAll(source)
)
/**
* @param {'div'|'span'|'canvas'|'p'|'a'|string} tagName
* @param {ElementCreationOptions} options
*/
search.new = search.newElement = (tagName, options) => (
$d.createElement(tagName, options)
)
/** @param {targetElement} target */
export function scrollTo(target) {
validHTML(target).scrollIntoView({ behavior: 'smooth' })
return target
}
/**
* @param {string|Image|HTMLImageElement} source
* @param {(base64: string) => void} [callback]
* @return {Promise<string>}
*/
export function getBase64(source, callback, outputFormat) {
if (typeof outputFormat !== 'string') {
outputFormat = 'image/png'
}
return new Promise((res, rej) => {
const image = new Image()
image.crossOrigin = 'Anonymous'
image.onerror = e => rej(e)
image.onload = () => {
try {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
canvas.height = image.naturalHeight
canvas.width = image.naturalWidth
ctx.drawImage(image, 0, 0)
res(canvas.toDataURL(outputFormat))
} catch (error) { rej(error) }
}
if (typeof source === 'string') {
image.src = source
} else if (source instanceof Image) {
image.src = source.src
} else {
rej(new TypeError('Not supported source param'))
}
}).then((base) => {
if (typeof callback === 'function') {
callback(base, source)
}
return base
})
}