欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

javascript填充默认头像方法

时间:2021-06-05 08:57:21|栏目:JavaScript代码|点击:

在我的不少项目中,都有缺省头像的问题。为了保持个性和方便辨认,会给没有头像的用户填充带名字的头像。

代码分享:https://github.com/joaner/namedavatar

调用简单

如果上传头像不存在,直接会在 <img> 标签上填充默认头像,用户名从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,&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;32&quot; height=&quot;32&quot;&gt;&lt;rect fill=&quot;#9C27B0&quot; x=&quot;0&quot; y=&quot;0&quot; width=&quot;100%&quot; height=&quot;100%&quot;&gt;&lt;/rect&gt;&lt;text fill=&quot;#FFF&quot; x=&quot;50%&quot; y=&quot;50%&quot; text-anchor=&quot;middle&quot; alignment-baseline=&quot;central&quot; font-size=&quot;16&quot; font-family=&quot;Verdana, Geneva, sans-serif&quot;&gt;Hanks&lt;/text&gt;&lt;/svg&gt;">

相比其它类似项目

  1. 首先对中文姓名的支持更好
  2. 直接在<img>标签上填充data URI,绿色无添加,应用成本更低
  3. 基于<svg>,没有用<canvas>渲染,性能也会好一点
  4. 支持的配置项更多,比如可以定义显示哪部分,或是随机背景颜色

也支持Vue.js的 directive 指令方式

import { directive } from 'namedavatar/vue'
// register as directive
Vue.directive('avatar', directive);
// in vue template
<template>
<img v-avatar="'Tom Hanks'" width="36"/>
</template>

上一篇:javascript 选择文件夹对话框(web)

栏    目:JavaScript代码

下一篇:浅谈webpack构建工具配置和常用插件总结

本文标题:javascript填充默认头像方法

本文地址:http://www.codeinn.net/misctech/135498.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有