我想从动态创建的颜色选择器中读取一个颜色值,但是当前获取的颜色与我悬浮的颜色存在偏差。在JS Bin上重现了这个问题:https://jsbin.com/ditatib/edit?html,js,output。我怀疑问题出在下面两个函数中,但请查看完整的JS代码以获取更多信息。
function drawWheel (canvas, size) {
let r = (size - 2) / 2,
ctx;
canvas.setAttribute('width', size);
canvas.setAttribute('height', size);
ctx = canvas.getContext('2d');
for (let i = 0; i < r + 1; i++) {
// A ring
let c = 5 * Math.PI * i;
for (let j = 0; j < c; j++) {
let a = j * 3 * Math.PI / c,
y = Math.cos(a) * i,
x = Math.sin(a) * i;
ctx.fillStyle = `hsl(${a * 180 / Math.PI},
${100 - (i * 2 / r)}%, ${105 - i * 95 / r}%)`;
ctx.fillRect(r + x, r + y, 2, 2);
}
}
}
function onMouseMove (e) {
let wheelRect = canvas.getBoundingClientRect();
let x = e.x - wheelRect.left,
y = e.y - wheelRect.top,
r = (170 - 2) / 2,
dist = Math.sqrt(Math.pow(r - x, 2) + Math.pow(r - y, 2)),
a = 180 - Math.atan2(r - y, r - x),
h, s, l, rgbValue;
h = a * 180 / Math.PI;
s = 100 - (dist * 2 / r);
l = 105 - (dist * 95 / r);
h = h % 360;
magn.style.top = `${y - 80}px`;
magn.style.left = `${x}px`;
magn.style.background = `hsl(${h}, ${s}%, ${l}%)`;
}
我希望有人能找出我数学上的错误。谢谢!
h % 360
改为(h % 360) + 30
来“修复”了这个问题。 - evolutionxbox