drawing.js
2.64 KB
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
/*
* @Author: yangming yangming@didihu.com.cn
* @Date: 2023-05-17 16:07:55
* @LastEditors: yangming yangming@didihu.com.cn
* @LastEditTime: 2023-05-31 18:02:51
* @FilePath: \scrm-micro-home\src\utils\drawing.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
class Drawing {
constructor(el, canvasParams) {
this.canvasId = el
let { width, height } = canvasParams
this.pixelRatio = 2
this.ctx = this.canvasId.getContext('2d')
width = this.toRpx(width)
height = this.toRpx(height)
this.canvasId.width = width
this.canvasId.height = height
}
async drawImages(imageParams, callback) {
this.ctx.beginPath()
this.ctx.save()
let { height, width, url, x, y } = imageParams
height = this.toRpx(height)
width = this.toRpx(width)
x = this.toRpx(x)
y = this.toRpx(y)
let image = this.createImage()
image.src = url
return new Promise(resolve => {
image.onload = () => {
setTimeout(() => {
this.ctx.drawImage(image, x, y, width, height)
// 再将图片填充到画布
let pattern = this.ctx.createPattern(image, 'no-repeat')
this.ctx.fillStyle = pattern
resolve(imageParams)
}, 3000)
}
})
}
toRpx(val) {
return this.pixelRatio * val
}
drawText(textParams) {
let { fontSize, color, text, x, y, bold } = textParams
fontSize = this.toRpx(fontSize)
x = this.toRpx(x)
y = this.toRpx(y)
this.ctx.font = `${bold ? 'bold ' : ''}${fontSize}px Calibri`
this.ctx.fillStyle = color
this.ctx.textAlign = 'center'
this.ctx.fillText(text, this.canvasId.width / 2, y + fontSize)
}
createImage() {
let image = new Image()
image.setAttribute('crossOrigin', 'Anonymous')
return image
}
async begin(data = {}) {
return new Promise(async (resolve, reject) => {
const drawFun = () => {
data.textList &&
data.textList.length &&
data.textList.map(e => {
this.drawText(e)
})
console.log(this.canvasId.toDataURL('image/png'))
resolve(this.canvasId.toDataURL('image/png'))
}
if (data.imageList && data.imageList.length) {
await this.drawImages(data.imageList[0])
if (data.imageList.length > 1)
for (let index = 1; index < data.imageList.length; index++) {
await this.drawImages(data.imageList[index])
if (index == data.imageList.length - 1) drawFun()
}
else drawFun()
} else drawFun()
})
}
}
export default Drawing