如何计算调色板中所选颜色的颜色?
How to calculate the color of the selected color in a color palette?
这是
的后续
之前,我对调色板中的选定像素使用 getImageData
来确定颜色是什么。然而,梯度并不总是完全准确。 Google's color picker 也是如此。他们的调色板并不完全准确,但他们 return 的颜色基于您在调色板中选择的位置 是 .
因此,假设此代码正在生成调色板:
function drawPalette(hue) {
var ctx = document.querySelector("canvas").getContext("2d");
let w = ctx.canvas.width;
let h = ctx.canvas.height;
var grH = ctx.createLinearGradient(0, 0, w, 0);
grH.addColorStop(0, '#fff');
grH.addColorStop(1, 'hsl(' + hue + ', 100%, 50%)');
ctx.fillStyle = grH;
ctx.fillRect(0, 0, w, h);
var grV = ctx.createLinearGradient(0, 0, 0, h);
grV.addColorStop(0, 'rgba(0,0,0,0)');
grV.addColorStop(1, '#000');
ctx.fillStyle = grV;
ctx.fillRect(0, 0, w, h);
}
drawPalette(120);
<canvas></canvas>
那么我如何确定 canvas 中任何给定坐标处的颜色? getImageData
将不起作用,因为它会稍微不准确。相反,我相信我需要一个函数,在给定色调、x 位置、y 位置、宽度和高度的情况下,return 调色板中该位置的颜色。这能做到吗?
您知道您的鼠标(或指针)位置在哪里(pointerdown,pointermove),因此您应该能够计算相对于您在上一个问题中构建的 canvas 的位置() 作为百分比(如果指针在 300px 宽的一半处 canvas,则为 50%,垂直位置也相同)。左下角为 0%、0%,右上角为 100%、100%。
百分比与色调相结合可以得出 HSV 值,其中:
H = hue
S = saturation = left to right percentage
V = value = bottom to top percentage
然后您可以使用以下方法将 HSV 值转换为 HSL 值:
function hsv2hsl(h, s, v) {
var l = v - (v * s) / 2;
var m = Math.min(l, 1 - l);
return [h, m ? (v - l) / m : 0, l];
}
如果鼠标在 canvas 的右侧,则该值为 100%。
这是
之前,我对调色板中的选定像素使用 getImageData
来确定颜色是什么。然而,梯度并不总是完全准确。 Google's color picker 也是如此。他们的调色板并不完全准确,但他们 return 的颜色基于您在调色板中选择的位置 是 .
因此,假设此代码正在生成调色板:
function drawPalette(hue) {
var ctx = document.querySelector("canvas").getContext("2d");
let w = ctx.canvas.width;
let h = ctx.canvas.height;
var grH = ctx.createLinearGradient(0, 0, w, 0);
grH.addColorStop(0, '#fff');
grH.addColorStop(1, 'hsl(' + hue + ', 100%, 50%)');
ctx.fillStyle = grH;
ctx.fillRect(0, 0, w, h);
var grV = ctx.createLinearGradient(0, 0, 0, h);
grV.addColorStop(0, 'rgba(0,0,0,0)');
grV.addColorStop(1, '#000');
ctx.fillStyle = grV;
ctx.fillRect(0, 0, w, h);
}
drawPalette(120);
<canvas></canvas>
那么我如何确定 canvas 中任何给定坐标处的颜色? getImageData
将不起作用,因为它会稍微不准确。相反,我相信我需要一个函数,在给定色调、x 位置、y 位置、宽度和高度的情况下,return 调色板中该位置的颜色。这能做到吗?
您知道您的鼠标(或指针)位置在哪里(pointerdown,pointermove),因此您应该能够计算相对于您在上一个问题中构建的 canvas 的位置(
百分比与色调相结合可以得出 HSV 值,其中:
H = hue
S = saturation = left to right percentage
V = value = bottom to top percentage
然后您可以使用以下方法将 HSV 值转换为 HSL 值:
function hsv2hsl(h, s, v) {
var l = v - (v * s) / 2;
var m = Math.min(l, 1 - l);
return [h, m ? (v - l) / m : 0, l];
}
如果鼠标在 canvas 的右侧,则该值为 100%。