SafeColor icon indicating copy to clipboard operation
SafeColor copied to clipboard

Avoid too similar colors

Open Kikobeats opened this issue 5 years ago • 6 comments

Hey, I really love this library, thanks for that 🙂

Screen Shot 2020-12-12 at 18 07 52

I want to ask if could be possible to add a way to avoid too similar colors since they look too close and in some context that is confuse

Kikobeats avatar Dec 12 '20 17:12 Kikobeats

Sorry for the late reply. As I'm currently working on other projects, I could't spare much effort in this one. If you have found the solution, a PR is always welcome :)

If you're not in a hurry, I might dive into the codes and improve the algorithm a bit later.

jessuni avatar Jan 04 '21 02:01 jessuni

Hey Jess, no rush!

I tried to improve the algorithm by myself but I don't understand the code too well 😅 so yea I can wait!

Kikobeats avatar Jan 04 '21 08:01 Kikobeats

@Kikobeats what worked for me was the following:

  1. Adding a variable that stores the previous color so that the color param for the new SafeColor always contrasts with the previous one.
  2. Passed a unique string id so that when I generate a random color it's unique :)

pmartiner avatar Feb 16 '21 19:02 pmartiner

@pmartiner that sounds smart!

Can you share the code snippet? 🙂

Kikobeats avatar Feb 16 '21 19:02 Kikobeats

Sure thing! My use case was rendering a Chart.js line chart with an automated color array with different and accessible colors, FYI.

        let prevColor: number[] = [255, 255, 255];

        const dataCampaignByDatesDataset = dataCampaignByDatesFiltered.map(obj => {
          const safeColor = new SafeColor({
            color: prevColor,
            contrast: 4.5,
          });
          const randomRgb = safeColor.random(obj.name);
          const rgbArray = randomRgb.substring(4, randomRgb.length - 1).split(',');
          const r = rgbArray[0];
          const g = rgbArray[1];
          const b = rgbArray[2];
          const alpha = 0.7;
          const rgb = `rgb(${r}, ${g}, ${b})`;
          const rgba = `rgb(${r}, ${g}, ${b}, ${alpha})`;
          prevColor = [r, g, b];

          return {
            label: obj.name,
            data: obj.amount,
            backgroundColor: rgba,
            borderColor: rgb,
            fill: 'start'
          };
        });

pmartiner avatar Feb 16 '21 19:02 pmartiner

@pmartiner wow, that's a smart workaround.

@Kikobeats what worked for me was the following:

  1. Adding a variable that stores the previous color so that the color param for the new SafeColor always contrasts with the previous one.
  2. Passed a unique string id so that when I generate a random color it's unique :)

jessuni avatar Feb 18 '21 03:02 jessuni