How to calculate the color of the selected color in a color palette?

一曲冷凌霜 提交于 2021-01-24 09:48:08

问题


This is a follow-up to this question I asked earlier

Previously, I was using getImageData on the selected pixel in the color palette to determine what the color is. However, the gradient will not always be perfectly accurate. This is even the case with Google's color picker. Their palette isn't entirely accurate, but the color they return based on your selected position in the color palette is.

So, assuming this code is generating the palette:

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>

Then how would I determine which color is present at any given coordinate in the canvas? getImageData will not work because it will be slightly inaccurate. Instead, I believe I need a function that, given a hue, an x position, a y position, a width, and a height, will return the color at that position in the color palette. Can this be done?


回答1:


You know where your mouse (or pointer) position is (pointerdown, pointermove), so you should be able to calculate the position relative to your canvas as you constructed it in your previous question (CSS Linear gradient is inaccurate?) as a percentage (if the pointer is half way across your 300px wide canvas, then 50%, and same for the vertical position). The lower left corner would be 0%, 0% and the upper right corner would be 100%, 100%.

The percentages combined with the hue would give you the HSV value where:

H = hue
S = saturation = left to right percentage
V = value = bottom to top percentage

Then you can convert the HSV value to HSL values using:

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];
}

If mouse is at the right side of the canvas, then the value will be 100%.



来源:https://stackoverflow.com/questions/65640099/how-to-calculate-the-color-of-the-selected-color-in-a-color-palette

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!