上传图片生成预览示例

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>

<input type="file" accept="image/*" multiple name="" id="uploadDom" maxlength="1" onchange="onFileChange()"/>
<script>
const onFileChange = () => {
console.log(uploadDom.files);
const binaryData = [];
binaryData.push(uploadDom.files[0]);
let objectURL = window.URL.createObjectURL(new Blob(binaryData));
var img = new Image();
img.src = objectURL;
document.getElementsByTagName('body')[0].appendChild(img)
img.onload = () => {
let zip = 5;
window.URL.revokeObjectURL(objectURL);
let canvas = document.createElement('canvas');
// let w = img.width;
// let h = img.height;
// if( w > h ){
// while (w > 600){
// w = w/2;
// h = h/2;
// }
// }else{
// while (h > 600){
// w = w/2;
// h = h/2;
// }
// }
// canvas.width = w;
// canvas.height = h;
canvas.width = img.width/zip;
canvas.height = img.height/zip;
canvas.getContext('2d').drawImage(img, 0, 0, img.width/zip, img.height/zip);
let b64 = canvas.toDataURL("image/png");
console.log(b64);
}


}

</script>

</body>
</html>

canvas/html2canvas生成海报时前端解决图片跨域

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 跨域解决
var img = new Image();
img.crossOrigin = "anonymous"; //重要,解决图片跨域的问题
img.src = _weatherDetail.imageUrl + '?time=' + new Date().valueOf();
img.onload = () => {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
console.log( canvas )
let dataURL = canvas.toDataURL('image/jpeg');
setBg(dataURL)
// console.log(img, dataURL)
}