javascript填充默認(rèn)頭像方法
更新時間:2018年02月22日 11:08:31 作者:joaner
本篇文章通過代碼實例給大家講述了如何javascript填充默認(rèn)頭像以及相代碼分享,對此有興趣的朋友可以學(xué)習(xí)下。
在我的不少項目中,都有缺省頭像的問題。為了保持個性和方便辨認(rèn),會給沒有頭像的用戶填充帶名字的頭像。
代碼分享:https://github.com/joaner/namedavatar
調(diào)用簡單
如果上傳頭像不存在,直接會在 <img> 標(biāo)簽上填充默認(rèn)頭像,用戶名從alt獲?。?/p>
<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>標(biāo)簽上填充data URI,綠色無添加,應(yīng)用成本更低
- 基于<svg>,沒有用<canvas>渲染,性能也會好一點(diǎn)
- 支持的配置項更多,比如可以定義顯示哪部分,或是隨機(jī)背景顏色
也支持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>
以上就是本次整理的全部內(nèi)容,感謝大家對腳本之家的支持。