1 <!DOCTYPE html>
2 <html lang="en">
3
4 <head>
5 <meta charset="UTF-8">
6 <title>Title</title>
7 </head>
8
9 <body>
10 <img src="img/bg.png" id="img1" style="display: block" width="750" height="1026" />
11 <img src="img/missing-face.png" id="img2" style="display: block" width="100" height="100" />
12 <img id="img3" />
13 <button onclick="draw()" id="btn">点击下载</button>
14 <script>
15 function draw() {
16 var img1 = document.getElementById("img1"),
17 img2 = document.getElementById("img2"),
18 img3 = document.getElementById("img3");
19 img1.width = 750;
20 img1.height = 1026;
21 img2.width = 100;
22 img2.height = 100;
23 var canvas = document.createElement("canvas"),
24 context = canvas.getContext("2d");
25 canvas.width = img1.width; // 绘制宽度
26 canvas.height = img1.height; // 绘制高度
27 // canvas.style.letterSpacing = '10px'; // 圆角
28 // 将 img1 加入画布
29 /**
30 * context.drawImage(image,x,y,w,h)
31 * image:Image对象var img=new Image(); img.src="url(...)";
32 * x:绘制图像的x坐标
33 * y:绘制图像的y坐标
34 * w:绘制图像的宽度
35 * h:绘制图像的高度
36 */
37 context.drawImage(img1, 0, 0, img1.width, img1.height);
38 // 将 img2 加入画布
39 context.drawImage(img2, 130, 800, img2.width, img2.height);
40 // 文字填充颜色
41 context.fillStyle = '#333';
42 // 文字字体
43 context.font = 'bold 45px Baoli SC';
44 // 设置文字
45 var name_text = '济 南 兴 国 寺';
46 // 获取文字的宽度 计算字体长度(px)
47 var name_width = context.measureText(name_text).width;
48 // 获取除去文本后的一半的宽度
49 var x = (canvas.width - name_width) / 2;
50 /**
51 * context.font:设置字体样式
52 * context.textAlign:水平对齐方式
53 * context.textBaseline:垂直对齐方式
54 * context.measureText(text):计算字体长度(px)
55 */
56 context.fillText(name_text, x, 450);
57 context.fillStyle = '#333'; // 文字填充颜色
58 context.font = '25px Baoli SC';
59 var desc_1 = '功德无量';
60 var desc_2 = '随缘乐助';
61 /**
62 * text:要绘制的文字
63 * x:文字起点的x坐标轴
64 * y:文字起点的y坐标轴
65 */
66 context.fillText(desc_1, x, 500);
67 var desc_width_2 = context.measureText(desc_2).width;
68 context.fillText(desc_2, canvas.width - x - desc_width_2, 500);
69 // 结束画图
70 context.stroke();
71 // 将画布内容导出
72 var src = canvas.toDataURL();
73 img3.src = src;
74 const a = document.createElement("a");
75 a.href = src;
76 a.download = '自定义文件名.png';
77 a.click();
78 }
79 </script>
80 </body>
81
82 </html>