'how to use color-thief in a vuejs context

I'm trying to import color-thief from NPM (https://github.com/lokesh/color-thief) like this:

import ColorThief from 'colorthief'

But when I call new ColorThief(), it returns something that it is not a constructor. console.log(ColorThief) just shows a _proto_ that I don't understand.

How can use the color-thief package properly?



Solution 1:[1]

Make sure to install null2/color-thief, which is a fork of the original project you linked that allows importing the package.

For example, you could use it in App.vue as follows:

  1. Install color-thief with:
npm install -S color-thief
  1. In App.vue's template, create an <img> tag that loads an image you want to analyze. Add a ref to the <img> so we could reference it in the next step.
<img ref="myImg" src="...">
  1. Import color-thief in your script, create an instance of ColorThief, and then use it to getPalette() on the <img>:
// App.vue
<script>
import ColorThief from 'color-thief'

export default {
  mounted() {
    this.$nextTick(() => {
      const colorThief = new ColorThief()
      const palette = colorThief.getPalette(this.$refs.myImg)
      /* do something with `palette` RGB array */
    })
  }
}
</script>

demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1