本篇文章通过代码实例给大家讲述了如何javascript填充默认头像以及相代码分享,对此有兴趣的朋友可以学习下。
在我的不少项目中,都有缺省头像的问题。为了保持个性和方便辨认,会给没有头像的用户填充带名字的头像。
代码分享:https://github.com/joaner/namedavatar
调用简单
如果上传头像不存在,直接会在 a1f02c36ba31691bcfe87b2722de723b 标签上填充默认头像,用户名从alt获取:
<img alt="李连杰" width="32" style="border-radius: 100%"><img src="./invalid.jpg" alt="tom hanks" width="40"><script>requirejs('namedavatar', function(namedavatar){ namedavatar.config({ nametype: 'lastname', }) namedavatar.setimgs(document.queryselectorall('img[alt]'), 'alt')})</script>
如果<img src="./invalid.jpg">资源无效,namedavatar.setimgs()就会填充alt里的用户名,src变成这样
<img id="avatar1" src="data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect fill="#9c27b0" x="0" y="0" width="100%" height="100%"></rect><text fill="#fff" x="50%" y="50%" text-anchor="middle" alignment-baseline="central" font-size="16" font-family="verdana, geneva, sans-serif">hanks</text></svg>">
相比其它类似项目
首先对中文姓名的支持更好
直接在<img>标签上填充data uri,绿色无添加,应用成本更低
基于<svg>,没有用<canvas>渲染,性能也会好一点
支持的配置项更多,比如可以定义显示哪部分,或是随机背景颜色
也支持vue.js的 directive 指令方式
import { directive } from 'namedavatar/vue'// register as directivevue.directive('avatar', directive);// in vue template<template><img v-avatar="'tom hanks'" width="36"/></template>
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
详细为你讲解immutable及 react 中实践技巧
如何解决vuex兼容ie上的报错问题(详细教程)
在node.js中使用readline如何实现逐行读取、写入文件内容
以上就是在javascript中如何实现填充默认头像的详细内容。