简体   繁体   中英

Colorthief.js with Polymer.js - finding the primary color of the image that caused the onload event

I am building a material web app with Polymer, and I want to get the primary and secondary colors of an image on the page. I'm using the on-click event to fire a function that retrieves the data from the image and gets the color. The problem is that the function works fine except for actually referring to the image -- ColorThief can't seem to 'see' the image. Here is my code:

Image:

<img style="opacity: 0;position: absolute;top:-100px;left:-100px;" width="1" height="1" data-albumno="{{i}}" src="{{root}}{{a.image}}" on-load="{{colorthis}}">

And the colorthis function:

Polymer('paper-albums', {
    colorthis: function(event, detail, sender) {
        var i = sender.dataset.albumno,
                cT = new ColorThief(),
                pallete = cT.getPalette(event.target, 2);

        //code to handle the pallete//
    }
});    

I believe the event.target is where the problem lies; I have tried using sender as well, but that didn't work either. What would I put here to refer to the image?

I have also tried creating the image in Javascript without putting it into the DOM, but to no avail. This seems like a simple task, but it has turned out to be far more complicated (at least to me). It's possible there is a better way entirely that I am missing.

As far as I can tell, your code should work as shown.

Here is a live example for Polymer 1.0: http://jsbin.com/vedowo/edit?html,output

Here is sample code:

<template>
  <img on-load="load" src="some-image.png">
</template>
<script>
  Polymer({
    is: 'x-example',
    load: function(e) {
      console.log(new ColorThief().getPalette(e.target, 2));
    }
  });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM