【发布时间】:2020-01-29 16:26:19
【问题描述】:
我想创建一个颜色选择器。如何将人点击的 x/y 坐标转换为实际的 rgb/hsv/hex/etc 颜色?
代码如下:
// jshint esnext:true
const palette = document.getElementsByClassName('fill-color-palette')[0]
palette.addEventListener('click', event => {
const x = event.clientX - palette.offsetLeft
const y = event.clientY - palette.offsetTop
console.log(x, y)
})
.grid {
display: grid;
padding: 5px;
grid-template-columns: 1fr 15px 15px;
column-gap: 10px;
}
.fill-color-palette {
position: relative;
height: 160px;
border-radius: 3px;
background-image: linear-gradient(rgb(0, 0, 0, 0), #000), linear-gradient(to right, #FFF, rgb(255, 255, 255, 0));
}
.fill-color-hue {
position: relative;
width: 15px;
height: 160px;
background: linear-gradient(to bottom, rgb(255, 0, 0), rgb(255, 0, 255), rgb(0, 0, 255), rgb(0, 255, 255), rgb(0, 255, 0), rgb(255, 255, 0), rgb(255, 0, 0));
border-radius: 3px;
}
.fill-color-alpha {
position: relative;
width: 15px;
height: 160px;
background: linear-gradient(to bottom, rgb(0, 0, 0) 0%, transparent 100%) 0% 0% no-repeat local, url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACpJREFUeNpi3LFjBwM2oK2tjVWciYFEMKqBGMCCK7yvXr06Gkr00wAQYACiEgXLqZw3aAAAAABJRU5ErkJggg==) 0 0 / 15px repeat local;
border-radius: 3px;
}
.pin {
position: absolute;
width: 15px;
height: 15px;
border: none;
border-radius: 11px;
background-color: #FFF;
box-shadow: rgb(51, 51, 51) 0px 0px 0px 1px inset, rgb(51, 51, 51) 0px 0px 0px 1px;
cursor: pointer;
}
.pin.active {
width: 11px;
height: 11px;
border: 2px solid #FFF;
background-color: transparent;
}
<div class="grid">
<div class="fill-color-palette" style="background-color: rgb(255, 0, 0);">
<div class="pin active"></div>
</div>
<div class="fill-color-hue">
<div class="pin active"></div>
</div>
<div class="fill-color-alpha">
<div class="pin active"></div>
</div>
</div>
https://jsbin.com/recayamaro/edit?html,css,js,console,output
【问题讨论】:
-
你为什么不用
<input type="color" />? -
我不确定它是不是真的。只需使用一些简单的颜色选择器
-
@connexo 我需要它用于自定义 UI 应用程序并且输入颜色太通用
-
我查看了来自光谱github.com/bgrins/spectrum/blob/master/spectrum.js#L752 的代码,它似乎采用了其中一个坐标,将其设置为当前色调,然后使用
tinycolor.fromRatio()获得纯色,然后将其转换十六进制。但我真的不明白这一切是如何运作的。也许有更多知识的人可以给我一些提示。 -
你不能使用常规的 HTML 元素,你需要一个画布才能工作。
标签: javascript css color-picker