js通过canvas多张图片合成图片来模仿微信的群头像并且转成base64
ChrisXie Lv5

刚好最近有个聊天室的项目,建群时候需要通过前端根据群成员头像生成群头像;结合了网上的一些资料也写了对应一个demo。

Demo

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>多张图片和合成</title>
</head>
<script type="text/javascript" src="../js/jquery.main.js"></script>
<body>
<img id="avatar" src="" width="30px"/>
</body>
<script>
var imageArry = ['../img/uimg/B_001.jpg','../img/uimg/B_002.jpg','../img/uimg/B_003.jpg','../img/uimg/B_004.jpg','../img/uimg/B_005.jpg','../img/uimg/B_006.jpg','../img/uimg/B_007.jpg','../img/uimg/B_008.jpg','../img/uimg/B_009.jpg'] ;
drawAndShareImage(imageArry);
function drawAndShareImage(imageArry){
var canvas = document.createElement("canvas");
//显示图片大小
canvas.width = 150;
canvas.height = 150;
var context = canvas.getContext("2d");
context.rect(0 , 0 , canvas.width , canvas.height);
context.fillStyle = "#fff";
context.fill();
var finished = 0;
for(var i = 0;i<imageArry.length;i++){
var $image = new Image();
$image.src = imageArry[i];
var loadImg = function($image, i) {
$image.onload = function() {
//根据图片张数拼接显示位置
if(i<3){
context.drawImage($image , (i*50) , 0 , 50 , 50);
context.rect((i*50) , 0 ,50,50);
}else if(i<6 && i >2){
context.drawImage($image , ((i-3)*50), 50 , 50 , 50);
context.rect((i-3)*50, 50,50,50);
}else if(i>=6){
context.drawImage($image , ((i-6)*50) , 100 , 50 , 50);
context.rect((i-6)*50 , 100,50,50);
}
//绘制边框
context.strokeStyle="rgba(232,232,232,0.2)";
context.lineWidth=2.5;
context.stroke();

finished ++;
if (finished === imageArry.length) {
var base64 = canvas.toDataURL("image/png"); //"image/png" 这里注意一下
var img = document.getElementById('avatar');
document.getElementById('avatar').src = base64;
img.setAttribute('src' , base64);
}
}
};
loadImg($image, i);
}
}
</script>
</html>


效果图片



头像本身可以通过canvas的width和height来控制base64的文件大小,当前最大9张合成后最大文件大小也控制在145kb左右

 评论