I am trying to read a color value from a dynamically created color wheel. However, there is a clear shift between the color that I get and the one that I am hanging over.
I recreated the JS Bin question:
https://jsbin.com/ditatib/edit?html,js,output
I suspect the problem is somewhere in the two functions below, but please see the JS bin for the full code.
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}%)`;
}
I would really appreciate it if someone could find where my math is wrong. Thank!
source
share