imgCanavs.js
3.03 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
85
86
87
88
89
90
91
let canvasRef = null
let ctx = null
export function dataInfo(deg, url) {
return new Promise((resolve, reject) => {
if (document.getElementById("imgViewCanvas")) {
canvasRef = document.getElementById("imgViewCanvas")
ctx = canvasRef.getContext('2d')
deg = deg
initCanvas(deg, url).then(res => {
resolve(res)
})
}
})
}
function getRotateParams(deg, width, height) {
const x =
(width / 2) * Math.cos((Math.PI * deg) / 180) +
(height / 2) * Math.sin((Math.PI * deg) / 180) -
width / 2
const y =
(Math.cos((Math.PI * deg) / 180) * height) / 2 -
(Math.sin((Math.PI * deg) / 180) * width) / 2 -
height / 2
return {
x,
y
}
}
function initCanvas(deg, url) {
return new Promise((resolve, reject) => {
if (ctx) {
const img = document.createElement('img')
img.crossOrigin = "Anonymous"
img.src = url
img.onload = () => {
if (deg == 90 || deg == 270) {
canvasRef.width = img.height
canvasRef.height = img.width
} else if (deg == 180) {
canvasRef.width = img.width
canvasRef.height = img.height
}
const imgAspectRatio = img.height / img.width
const imgWidth = img.width
const imgHeight = imgWidth * imgAspectRatio
const { x, y } = getRotateParams(deg, canvasRef.width, canvasRef.height)
ctx?.rotate((deg * Math.PI) / 180)
ctx?.translate(x, y)
ctx?.drawImage(
img,
(canvasRef.width - imgWidth) / 2,
(canvasRef.height - imgHeight) / 2,
imgWidth,
imgHeight,
)
// canvasRef.toDataURL('image/jpeg', 0.5)
canvasRef.toBlob((blob) => {
resolve(blob)
// const aLink = document.createElement('a')
// aLink.href = URL.createObjectURL(blob)
console.log(URL.createObjectURL(blob))
// aLink.setAttribute('download', 'xxxx') // 设置下载文件名称
// document.body.appendChild(aLink)
// aLink.click()
// document.body.removeChild(aLink);
ctx.fillRect(0, 0, 0, 0)
}, 'image/jpeg', 0.9)
}
}
})
}
// // 0. 获取到页面上的 canvas 标签元素节点
// const canvasEle = document.querySelector('#canvas')
// // 1. 获取当前这个画布的工具箱
// const ctx = canvasEle.getContext('2d')
// // 2. 加载图片
// myImg.sec = './01小锋.png'
// // 准备一个加载完毕的事件
// myImg.onload = function () {
// console.log(this) // 这里的 this 就是这个图片的内容
// // 3. 插入到画布内
// ctx.drawImage(this, 100, 100, 236, 368)
// }