最近个人项目中有头像需求,就想起GitHub的随机头像,通过identicon.jsblueimp-md5两个第三方库实现了,记录一下。

实现效果

封装组件

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
<template>
<img class="avatar" :src="url">
</template>

<script>
import Identicon from 'identicon.js'
import md5 from 'blueimp-md5'

export default {
props: {
num: [Number]
},
computed: {
url() {
return 'data:image/png;base64,' + new Identicon(md5(this.num || 0), 420).toString()
}
}
}
</script>

<style lang="scss" scoped>
.avatar {
width: 40px;
height: 40px;
border-radius: 50%;
}
</style>

注意点

  • 第15行的new Identicon(...)必须使用new初始化,具体原因还不清楚,如果有人清楚欢迎在下方评论。

参考资料