Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Concept: Extract most frequently used color #228

Open
topada opened this issue May 15, 2020 · 1 comment
Open

Concept: Extract most frequently used color #228

topada opened this issue May 15, 2020 · 1 comment

Comments

@topada
Copy link

topada commented May 15, 2020

Hi there,
I have been working on an extension that analyses eight samples along the edge of the canvas and extracts the most frequently used color, excluding white. I am trying to extend uploaded brand logos in case they have a colored background and cannot be scaled.

Maybe this concept could spark a new feature idea for the vue-croppa plugin?

Cheers, Jonas

sample-spots

methods: {
    onDraw: function(ctx) {
      //https://bit.ly/2Zf1lth

      //get canvas dimensions
      let { width, height } = ctx.canvas;

      //define sample spots
      let sampleSpots = [
        [0, 0],
        [width * 0.5, 0],
        [width - 1, 0],
        [width - 1, height * 0.5],
        [width - 1, height - 1],
        [width * 0.5, height - 1],
        [0, height - 1],
        [0, height * 0.5]
      ];

      //get samples
      let samples = [];
      let samplesHex = [];
      for (let i = 0; i < sampleSpots.length; i++) {
        //console.log("sample:", i, sampleSpots[i][0]);

        let px = ctx.getImageData(
          sampleSpots[i][0], //x
          sampleSpots[i][1], //y
          1, //w
          1 //h
        ).data;

        samples[i] = px;
        samplesHex[i] =
          "#" + ("000000" + this.rgbToHex(px[0], px[1], px[2])).slice(-6);
      }

      // console.log("sH:", samplesHex);
      // console.log("mode:", this.mode(samplesHex));

      //filter White samples from Array
      let samplesHexColor = samplesHex.filter(e => e !== "#ffffff");

      // console.log("sHColor:", samplesHexColor);
      // console.log("mode:", this.mode(samplesHexColor));

      this.canvasColor = this.mode(samplesHexColor);
    },
    //https://bit.ly/2Zf1lth
    rgbToHex: function(r, g, b) {
      if (r > 255 || g > 255 || b > 255) throw "Invalid color component";
      return ((r << 16) | (g << 8) | b).toString(16);
    },
    //https://bit.ly/2WwF2NK
    mode: function(arr) {
      return arr
        .sort(
          (a, b) =>
            arr.filter(v => v === a).length - arr.filter(v => v === b).length
        )
        .pop();
    }
}`
@micardona96
Copy link

I like it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants