图片转base64
邵预鸿 Lv5
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
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>

<body>

</body>

</html>
<script>
function createCanvas() {
var canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
canvas.style.border = "1px solid red";
document.body.appendChild(canvas);
}

function setCanvasBg() {
var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0, 100, 100);
ctx.lineWidth = 1;
ctx.lineCap = "round";
ctx.strokeStyle = 'red';
ctx.moveTo(20, 80);
ctx.lineTo(80, 80);
ctx.stroke();
ctx.fillStyle = '#fff';
ctx.font = "16px Georgia";
ctx.textAlign = "center";
ctx.fillText("shao", 50, 95);
}

function toBase64() {
var canvas = document.querySelector("canvas");
var base64 = canvas.toDataURL("image/jpeg");
return base64;
}
var image = new Image();
image.src = "./u=1610542142,718703573&fm=26&gp=0.jpg";
image.setAttribute('crossOrigin', 'anonymous');
image.onload = function () {
createCanvas();
setCanvasBg();
document.body.style.backgroundImage = `url(${toBase64()})`;
document.querySelector("canvas").remove();
}
</script>
  • 本文标题:图片转base64
  • 本文作者:邵预鸿
  • 创建时间:2021-02-21 12:02:14
  • 本文链接:/images/logo.jpg2021/02/21/图片转base64/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!