AccountInitialAvatar.vue 1.3 KB

12345678910111213141516171819202122232425262728293031323334
  1. <script setup lang="ts">
  2. import { computed } from 'vue'
  3. const props = withDefaults(defineProps<{
  4. name: string
  5. imageUrl?: string
  6. size?: number
  7. }>(), { imageUrl: '', size: 30 })
  8. const initial = computed(() => Array.from(props.name.trim())[0]?.toLocaleUpperCase() || '?')
  9. const colors = ['#1488ff', '#00a17a', '#9655f7', '#e05d2f', '#b7791f', '#5166d6'] as const
  10. const background = computed(() => {
  11. let hash = 2166136261
  12. for (const byte of new TextEncoder().encode(props.name.trim().toLocaleLowerCase() || '?')) {
  13. hash ^= byte
  14. hash = Math.imul(hash, 16777619) >>> 0
  15. }
  16. return colors[hash % colors.length]
  17. })
  18. </script>
  19. <template>
  20. <span
  21. class="account-initial-avatar"
  22. :style="{ width: `${size}px`, height: `${size}px`, backgroundColor: background, fontSize: `${Math.max(11, Math.round(size * .42))}px` }"
  23. role="img"
  24. :aria-label="`${name || '当前账号'} 的账号头像`"
  25. ><img v-if="imageUrl" :src="imageUrl" alt="" /><span v-else aria-hidden="true">{{ initial }}</span></span>
  26. </template>
  27. <style scoped>
  28. .account-initial-avatar { display: inline-grid; flex: 0 0 auto; place-items: center; border-radius: 50%; color: #fff; font-weight: 700; line-height: 1; text-transform: uppercase; user-select: none; }
  29. .account-initial-avatar img { width: 100%; height: 100%; border-radius: inherit; object-fit: cover; }
  30. </style>