在个人很多项目中,都有缺省头像的问题。为了保持个性和方便辨认,会给没有头像的用户填充带名字的头像。vue
github项目: https://github.com/joaner/nam...git
若是上传头像不存在,直接会在 <img>
标签上填充默认头像,用户名从alt
获取:github
<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
变成这样canvas
<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>">
import { directive } from 'namedavatar/vue' // register as directive Vue.directive('avatar', directive); // in vue template <template> <img v-avatar="'Tom Hanks'" width="36"/> </template>