lokesh / color-thief

Grab the color palette from an image using just Javascript. Works in the browser and in Node.
https://lokeshdhakar.com/projects/color-thief/
MIT License
12.49k stars 1.31k forks source link

Suggestion: Allow to pass video or canvas instead just image element type #197

Closed vladmandic closed 2 years ago

vladmandic commented 4 years ago

As the subject line says, color-thief creates canvas from an image param. In some cases, I already have canvas created from the image, would be great if I could pass it as-is.

Quick hack - this also allows color-thief to work with image, canvas or video elements:

/*
  CanvasImage Class
  Class that wraps the html image/canvas/video element and internal canvas.
  It also simplifies some of the canvas context manipulation
  with a set of helper functions.
*/

const CanvasImage = function (element) {
    if (element.nodeName === 'CANVAS') {
        this.canvas = element;
        this.context = element.getContext('2d');
        this.width  = element.width;
        this.height = element.height;
    } else if (element.nodeName === 'VIDEO') {
        this.canvas  = document.createElement('canvas');
        this.context = this.canvas.getContext('2d');
        this.width  = this.canvas.width  = video.videoWidth;
        this.height = this.canvas.height = element.videoHeight;
        this.context.drawImage(element, 0, 0, this.width, this.height);
    } else {
        this.canvas  = document.createElement('canvas');
        this.context = this.canvas.getContext('2d');
        this.width  = this.canvas.width  = element.naturalWidth;
        this.height = this.canvas.height = element.naturalHeight;
        this.context.drawImage(element, 0, 0, this.width, this.height);
    }
};

https://github.com/lokesh/color-thief/pull/198

vladmandic commented 2 years ago

closing as no update from maintainer for over a year.

marcanw commented 3 months ago

Thx for the hack ;-)