根据背景颜色明暗度切换字体(黑白)颜色(vue3示例)

更新于 2023-11-22 20:53 74
专栏: 前端文章 标签: vue

  1. <script setup lang="ts">
  2. import { computed, ref } from 'vue'
  3. import { NColorPicker } from 'naive-ui'
  4. // 获取背景颜色的 RGB 值(假设这里获取到了背景颜色的值)
  5. const bgColor = ref('#000000') // 假设为蓝色
  6. // 计算颜色的明暗度
  7. const calculateLuminance = (color: string) => {
  8. const hex = color.replace(/^#/, '')
  9. const r = parseInt(hex.substring(0, 2), 16)
  10. const g = parseInt(hex.substring(2, 4), 16)
  11. const b = parseInt(hex.substring(4, 6), 16)
  12. return (0.299 * r + 0.587 * g + 0.114 * b) / 255
  13. }
  14. // 根据明暗度切换文本颜色
  15. const textColor = computed(() => {
  16. const luminance = calculateLuminance(bgColor.value)
  17. return luminance > 0.5 ? 'black' : 'white'
  18. })
  19. </script>
  20. <template>
  21. <div :style="{ backgroundColor: bgColor, color: textColor }">
  22. Background Color Example
  23. </div>
  24. <NColorPicker v-model:value="bgColor" />
  25. </template>
  26. <style scoped>
  27. /* 样式可以根据实际需求自定义 */
  28. div {
  29. width: 200px;
  30. height: 100px;
  31. display: flex;
  32. justify-content: center;
  33. align-items: center;
  34. font-size: 18px;
  35. }
  36. </style>

BLOG

搜索文章