index.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. <template>
  2. <div class="color-picker">
  3. <div class="picker-saturation-wrap">
  4. <Saturation :value="color" :hue="hue" @colorChange="value => changeColor(value)" />
  5. </div>
  6. <div class="picker-controls">
  7. <div class="picker-color-wrap">
  8. <div class="picker-current-color" :style="{ background: currentColor }"></div>
  9. <Checkboard />
  10. </div>
  11. <div class="picker-sliders">
  12. <div class="picker-hue-wrap">
  13. <Hue :value="color" :hue="hue" @colorChange="value => changeColor(value)" />
  14. </div>
  15. <div class="picker-alpha-wrap">
  16. <Alpha :value="color" @colorChange="value => changeColor(value)" />
  17. </div>
  18. </div>
  19. </div>
  20. <div class="picker-field">
  21. <EditableInput class="input" :value="color" @colorChange="value => changeColor(value)" />
  22. <div class="straw" @click="openEyeDropper()"><IconNeedle /></div>
  23. <div class="transparent" @click="selectPresetColor('#00000000')">
  24. <Checkboard />
  25. </div>
  26. </div>
  27. <div class="picker-presets">
  28. <div
  29. class="picker-presets-color"
  30. v-for="c in themeColors"
  31. :key="c"
  32. :style="{ background: c }"
  33. @click="selectPresetColor(c)"
  34. ></div>
  35. </div>
  36. <div class="picker-gradient-presets">
  37. <div
  38. class="picker-gradient-col"
  39. v-for="(col, index) in presetColors"
  40. :key="index"
  41. >
  42. <div class="picker-gradient-color"
  43. v-for="c in col"
  44. :key="c"
  45. :style="{ background: c }"
  46. @click="selectPresetColor(c)"
  47. ></div>
  48. </div>
  49. </div>
  50. <div class="picker-presets">
  51. <div
  52. v-for="c in standardColors"
  53. :key="c"
  54. class="picker-presets-color"
  55. :style="{ background: c }"
  56. @click="selectPresetColor(c)"
  57. ></div>
  58. </div>
  59. <div class="recent-colors-title" v-if="recentColors.length">最近使用:</div>
  60. <div class="picker-presets">
  61. <div
  62. v-for="c in recentColors"
  63. :key="c"
  64. class="picker-presets-color alpha"
  65. @click="selectPresetColor(c)"
  66. >
  67. <div class="picker-presets-color-content" :style="{ background: c }"></div>
  68. </div>
  69. </div>
  70. </div>
  71. </template>
  72. <script lang="ts" setup>
  73. import { computed, onMounted, ref, watch } from 'vue'
  74. import tinycolor, { type ColorFormats } from 'tinycolor2'
  75. import { debounce } from 'lodash'
  76. import { toCanvas } from 'html-to-image'
  77. import message from '@/utils/message'
  78. import Alpha from './Alpha.vue'
  79. import Checkboard from './Checkboard.vue'
  80. import Hue from './Hue.vue'
  81. import Saturation from './Saturation.vue'
  82. import EditableInput from './EditableInput.vue'
  83. const props = withDefaults(defineProps<{
  84. modelValue?: string
  85. }>(), {
  86. modelValue: '#e86b99',
  87. })
  88. const emit = defineEmits<{
  89. (event: 'update:modelValue', payload: string): void
  90. }>()
  91. const RECENT_COLORS = 'RECENT_COLORS'
  92. const presetColorConfig = [
  93. ['#7f7f7f', '#f2f2f2'],
  94. ['#0d0d0d', '#808080'],
  95. ['#1c1a10', '#ddd8c3'],
  96. ['#0e243d', '#c6d9f0'],
  97. ['#233f5e', '#dae5f0'],
  98. ['#632623', '#f2dbdb'],
  99. ['#4d602c', '#eaf1de'],
  100. ['#3f3150', '#e6e0ec'],
  101. ['#1e5867', '#d9eef3'],
  102. ['#99490f', '#fee9da'],
  103. ]
  104. const gradient = (startColor: string, endColor: string, step: number) => {
  105. const _startColor = tinycolor(startColor).toRgb()
  106. const _endColor = tinycolor(endColor).toRgb()
  107. const rStep = (_endColor.r - _startColor.r) / step
  108. const gStep = (_endColor.g - _startColor.g) / step
  109. const bStep = (_endColor.b - _startColor.b) / step
  110. const gradientColorArr = []
  111. for (let i = 0; i < step; i++) {
  112. const gradientColor = tinycolor({
  113. r: _startColor.r + rStep * i,
  114. g: _startColor.g + gStep * i,
  115. b: _startColor.b + bStep * i,
  116. }).toRgbString()
  117. gradientColorArr.push(gradientColor)
  118. }
  119. return gradientColorArr
  120. }
  121. const getPresetColors = () => {
  122. const presetColors = []
  123. for (const color of presetColorConfig) {
  124. presetColors.push(gradient(color[1], color[0], 5))
  125. }
  126. return presetColors
  127. }
  128. const themeColors = ['#000000', '#ffffff', '#eeece1', '#1e497b', '#4e81bb', '#e2534d', '#9aba60', '#8165a0', '#47acc5', '#f9974c']
  129. const standardColors = ['#c21401', '#ff1e02', '#ffc12a', '#ffff3a', '#90cf5b', '#00af57', '#00afee', '#0071be', '#00215f', '#72349d']
  130. const hue = ref(-1)
  131. const recentColors = ref<string[]>([])
  132. const color = computed({
  133. get() {
  134. return tinycolor(props.modelValue).toRgb()
  135. },
  136. set(rgba: ColorFormats.RGBA) {
  137. const rgbaString = `rgba(${[rgba.r, rgba.g, rgba.b, rgba.a].join(',')})`
  138. emit('update:modelValue', rgbaString)
  139. },
  140. })
  141. const presetColors = getPresetColors()
  142. const currentColor = computed(() => {
  143. return `rgba(${[color.value.r, color.value.g, color.value.b, color.value.a].join(',')})`
  144. })
  145. const selectPresetColor = (colorString: string) => {
  146. hue.value = tinycolor(colorString).toHsl().h
  147. emit('update:modelValue', colorString)
  148. }
  149. // 每次选择非预设颜色时,需要将该颜色加入到最近使用列表中
  150. const updateRecentColorsCache = debounce(function() {
  151. const _color = tinycolor(color.value).toRgbString()
  152. if (!recentColors.value.includes(_color)) {
  153. recentColors.value = [_color, ...recentColors.value]
  154. const maxLength = 10
  155. if (recentColors.value.length > maxLength) {
  156. recentColors.value = recentColors.value.slice(0, maxLength)
  157. }
  158. }
  159. }, 300, { trailing: true })
  160. onMounted(() => {
  161. const recentColorsCache = localStorage.getItem(RECENT_COLORS)
  162. if (recentColorsCache) recentColors.value = JSON.parse(recentColorsCache)
  163. })
  164. watch(recentColors, () => {
  165. const recentColorsCache = JSON.stringify(recentColors.value)
  166. localStorage.setItem(RECENT_COLORS, recentColorsCache)
  167. })
  168. const changeColor = (value: ColorFormats.RGBA | ColorFormats.HSLA | ColorFormats.HSVA) => {
  169. if ('h' in value) {
  170. hue.value = value.h
  171. color.value = tinycolor(value).toRgb()
  172. }
  173. else {
  174. hue.value = tinycolor(value).toHsl().h
  175. color.value = value
  176. }
  177. updateRecentColorsCache()
  178. }
  179. // 打开取色吸管
  180. // 检查环境是否支持原生取色吸管,支持则使用原生吸管,否则使用自定义吸管
  181. const openEyeDropper = () => {
  182. const isSupportedEyeDropper = 'EyeDropper' in window
  183. if (isSupportedEyeDropper) browserEyeDropper()
  184. else customEyeDropper()
  185. }
  186. // 原生取色吸管
  187. const browserEyeDropper = () => {
  188. message.success('按 ESC 键关闭取色吸管', { duration: 0 })
  189. // eslint-disable-next-line
  190. const eyeDropper = new (window as any).EyeDropper()
  191. eyeDropper.open().then((result: { sRGBHex: string }) => {
  192. const tColor = tinycolor(result.sRGBHex)
  193. hue.value = tColor.toHsl().h
  194. color.value = tColor.toRgb()
  195. message.closeAll()
  196. updateRecentColorsCache()
  197. }).catch(() => {
  198. message.closeAll()
  199. })
  200. }
  201. // 基于 Canvas 的自定义取色吸管
  202. const customEyeDropper = () => {
  203. const targetRef: HTMLElement | null = document.querySelector('.canvas')
  204. if (!targetRef) return
  205. const maskRef = document.createElement('div')
  206. maskRef.style.cssText = 'position: fixed; top: 0; left: 0; bottom: 0; right: 0; z-index: 9999; cursor: wait;'
  207. document.body.appendChild(maskRef)
  208. const colorBlockRef = document.createElement('div')
  209. colorBlockRef.style.cssText = 'position: absolute; top: -100px; left: -100px; width: 16px; height: 16px; border: 1px solid #000; z-index: 999'
  210. maskRef.appendChild(colorBlockRef)
  211. const { left, top, width, height } = targetRef.getBoundingClientRect()
  212. const filter = (node: HTMLElement) => {
  213. if (node.tagName && node.tagName.toUpperCase() === 'FOREIGNOBJECT') return false
  214. if (node.classList && node.classList.contains('operate')) return false
  215. return true
  216. }
  217. toCanvas(targetRef, { filter, fontEmbedCSS: '', width, height, canvasWidth: width, canvasHeight: height, pixelRatio: 1 }).then(canvasRef => {
  218. canvasRef.style.cssText = `position: absolute; top: ${top}px; left: ${left}px; cursor: crosshair;`
  219. maskRef.style.cursor = 'default'
  220. maskRef.appendChild(canvasRef)
  221. const ctx = canvasRef.getContext('2d')
  222. if (!ctx) return
  223. let currentColor = ''
  224. const handleMousemove = (e: MouseEvent) => {
  225. const x = e.x
  226. const y = e.y
  227. const mouseX = x - left
  228. const mouseY = y - top
  229. const [r, g, b, a] = ctx.getImageData(mouseX, mouseY, 1, 1).data
  230. currentColor = `rgba(${r}, ${g}, ${b}, ${(a / 255).toFixed(2)})`
  231. colorBlockRef.style.left = x + 10 + 'px'
  232. colorBlockRef.style.top = y + 10 + 'px'
  233. colorBlockRef.style.backgroundColor = currentColor
  234. }
  235. const handleMouseleave = () => {
  236. currentColor = ''
  237. colorBlockRef.style.left = '-100px'
  238. colorBlockRef.style.top = '-100px'
  239. colorBlockRef.style.backgroundColor = ''
  240. }
  241. const handleMousedown = (e: MouseEvent) => {
  242. if (currentColor && e.button === 0) {
  243. const tColor = tinycolor(currentColor)
  244. hue.value = tColor.toHsl().h
  245. color.value = tColor.toRgb()
  246. updateRecentColorsCache()
  247. }
  248. document.body.removeChild(maskRef)
  249. canvasRef.removeEventListener('mousemove', handleMousemove)
  250. canvasRef.removeEventListener('mouseleave', handleMouseleave)
  251. window.removeEventListener('mousedown', handleMousedown)
  252. }
  253. canvasRef.addEventListener('mousemove', handleMousemove)
  254. canvasRef.addEventListener('mouseleave', handleMouseleave)
  255. window.addEventListener('mousedown', handleMousedown)
  256. }).catch(() => {
  257. message.error('取色吸管初始化失败')
  258. document.body.removeChild(maskRef)
  259. })
  260. }
  261. </script>
  262. <style lang="scss" scoped>
  263. .color-picker {
  264. position: relative;
  265. width: 240px;
  266. background: #fff;
  267. user-select: none;
  268. margin-bottom: -10px;
  269. }
  270. .picker-saturation-wrap {
  271. width: 100%;
  272. padding-bottom: 50%;
  273. position: relative;
  274. overflow: hidden;
  275. }
  276. .picker-controls {
  277. display: flex;
  278. }
  279. .picker-sliders {
  280. padding: 4px 0;
  281. flex: 1;
  282. }
  283. .picker-hue-wrap {
  284. position: relative;
  285. height: 10px;
  286. }
  287. .picker-alpha-wrap {
  288. position: relative;
  289. height: 10px;
  290. margin-top: 4px;
  291. overflow: hidden;
  292. }
  293. .picker-color-wrap {
  294. width: 24px;
  295. height: 24px;
  296. position: relative;
  297. margin-top: 4px;
  298. margin-right: 4px;
  299. outline: 1px dashed rgba($color: #666, $alpha: .12);
  300. .checkerboard {
  301. background-size: auto;
  302. }
  303. }
  304. .picker-current-color {
  305. @include absolute-0();
  306. z-index: 2;
  307. }
  308. .picker-field {
  309. display: flex;
  310. margin-bottom: 8px;
  311. .transparent {
  312. width: 24px;
  313. height: 24px;
  314. margin-top: 4px;
  315. margin-left: 8px;
  316. position: relative;
  317. cursor: pointer;
  318. &::after {
  319. content: '';
  320. width: 26px;
  321. height: 2px;
  322. position: absolute;
  323. top: 11px;
  324. left: -1px;
  325. transform: rotate(-45deg);
  326. background-color: #f00;
  327. }
  328. .checkerboard {
  329. background-size: auto;
  330. }
  331. }
  332. .straw {
  333. width: 24px;
  334. height: 24px;
  335. margin-top: 4px;
  336. margin-left: 8px;
  337. display: flex;
  338. justify-content: center;
  339. align-items: center;
  340. font-size: 20px;
  341. background-color: #f5f5f5;
  342. outline: 1px solid #f1f1f1;
  343. cursor: pointer;
  344. }
  345. .input {
  346. flex: 1;
  347. }
  348. }
  349. .picker-presets {
  350. @include flex-grid-layout();
  351. }
  352. .picker-presets-color {
  353. @include flex-grid-layout-children(10, 7%);
  354. height: 0;
  355. padding-bottom: 7%;
  356. flex-shrink: 0;
  357. position: relative;
  358. cursor: pointer;
  359. &.alpha {
  360. background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAADBJREFUOE9jfPbs2X8GPEBSUhKfNAPjqAHDIgz+//+PNx08f/4cfzoYNYCBceiHAQC5flV5JzgrxQAAAABJRU5ErkJggg==);
  361. }
  362. }
  363. .picker-presets-color-content {
  364. @include absolute-0();
  365. }
  366. .picker-gradient-presets {
  367. @include flex-grid-layout();
  368. }
  369. .picker-gradient-col {
  370. @include flex-grid-layout-children(10, 7%);
  371. display: flex;
  372. flex-direction: column;
  373. }
  374. .picker-gradient-color {
  375. width: 100%;
  376. height: 16px;
  377. position: relative;
  378. cursor: pointer;
  379. }
  380. .recent-colors-title {
  381. font-size: 12px;
  382. margin-bottom: 4px;
  383. }
  384. </style>