颜色选择器环的纯 css 实现(单应用程序版本)
最编程
2024-03-30 14:04:30
...
效果
取色盘样式
css
`
.dialog {
display: block;
border-radius: 30rpx;
/* background-color: #FFF; */
background-color: transparent;
margin: 20rpx;
padding: 0 30rpx;
}
.colorBg {
width: 80vw;
height: 80vw;
margin: 0 5vw;
background: conic-gradient(red,
yellow,
lime,
aqua,
blue,
fuchsia,
red);
border-radius: 50%;
position: relative;
display: flex;
justify-content: center;
align-items: center;
}
.roundBuff {
width: 40vw;
height: 40vw;
-webkit-transform-origin: center 50%;
transform-origin: center 50%;
background: #fff;
border-radius: 50%;
}
`
取色交互
当手指在取色盘上移动时,计算手指点击的点和圆盘中心点的夹角,用夹角大小去计算r,g,b三个颜色通道的值
我们以触摸点与Y轴正半轴的夹角来计算,以红色R为例子
当夹角大于300度,或者小于60度时,值是255
当角度从60到120度时,色值越来越
角度大于120度且小于240度时为0小
当角度从120到300度时,色值越来越大
用函数表示
getColorByDeg(deg) {
const r = this.getCos(deg) * 255
const g = this.getCos(deg + 240) * 255
const b = this.getCos(deg + 120) * 255
return `rgb(${r},${g},${b})`
},
getCos (degOrg) {
const deg = degOrg % 360
if (deg > 300 || deg <= 60) return 1
if (deg > 120 && deg <= 240) return 0
if (deg > 60 && deg <= 120) {
// 变小
//(deg - 60) * (3 / 2)
return Math.cos(this.getRadianByDeg((deg - 60) * (3 / 2)))
} else {
// 变大
// (deg - 300) * (3 / 2)
return Math.cos(this.getRadianByDeg((deg - 300) * (3 / 2)))
}
},
// 弧度转角度
getRadianByDeg(deg) {
return Math.PI/180 * deg
},
得到触摸点与圆心的夹角
uni.getSystemInfo({
success: (res) => {
const query = uni.createSelectorQuery().in(this);
query.select('#colorBg').boundingClientRect(rect => {
self.pointerBox = rect
}).exec()
self.colorPanRadius = res.screenWidth * 0.4
}
})
startTouch(e) {
const {
pageX,
pageY
} = e.touches[0]
console.log(e.touches[0])
this.rotatePointer(pageX, pageY)
},
rotatePointer(pageX = 0, pageY = 0) {
const {
pointerBox,
colorPanWidth
} = this
const mouseX = pageX// - colorPanWidth
const mouseY = pageY// - colorPanWidth
var centerY = pointerBox.top + (pointerBox.height / 2) - 0, // 中心点
centerX = pointerBox.left + (pointerBox.height / 2) - 0, // 中心点
radians = Math.atan2(mouseY - centerY, mouseX - centerX) // 坐标系中任意一个点(x, y)和原点(0, 0)的连线与X轴正半轴的夹角大小的弧度
this.degrees = radians * (180 / Math.PI) + 90
},