流星和颜色贼won'一起工作

Meteor and Color Thief won' work together

本文关键字:一起 工作 won 颜色 流星      更新时间:2023-09-26

我一直在使用meteor创建一个显示音乐专辑列表的小项目。现在,音乐专辑数据存储在模板助手中,如下所示:

    var albumsData = [
      {
        artist:'artist name',
        title: 'title album',
        url: 'http://...',
        review: 'Lore ipsum',
        sauce:'lostyears.png'
      }, ...
];
Template.albumsList.helpers({
  albums: albumsData
});

和相对于它的模板部分是:

 <div class="album-info">
    <div class="unit size3of5">
        <h6>{{artist}}</h6>
        <h2 id="primaryColor">{{title}}</h2>
        <a href="{{url}}" class="secondaryColor">Listen on...</a>
        <p>{{review}}</p>
    </div> 
    <div class="unit size2of5">
       <div class="album-Image">
         <img id="myImg" src="{{sauce}}">
       </div>
    </div>
</div>

请注意,我不需要指定图像的方向,因为meteor会自动找到项目内/public文件夹中的所有图像。

在html模板中,就在前面显示的html片段之后,我已经这样使用了color thief:

<script>
  $(window).ready(function(){
    var colorThief = new ColorThief();
    var color = colorThief.getColor('{{sauce}}');
    document.getElementById("primaryColor").style.color = "rgb(" + color + ")";
   });
</script>

专辑列表显示正确的颜色小偷似乎不工作,无论我做什么,这可能会让我认为,如果有一些关于流星我不知道。还想提醒一下,偷颜色的人。.j和Quantize.js包含在client文件夹中。

谢谢大家

编辑:由于流星处理逻辑和模板在单独的文件,我创建了一个新的模板助手,以这种方式:

    Template.albumItem.helpers({
  color: function() {
    var colorThief = new ColorThief();
    return colorThief.getColor(this.sauce);
  }
});

在模板albumItem中使用color:

<h2 style="color:{{ color }}">{{title}}</h2>

仍然不工作,但我确信这是一个正确的方向,也许现在我们需要弄清楚如何知道这个模板开始后的图像加载…

尝试将var color = colorThief.getColor('{{sauce}}');替换为var color = colorThief.getColor($('#myImg'));

我让它与以下代码一起工作。

{{#each albums}}
    {{> ImageBanner}}
{{/each}}

图片横幅模板是(请编辑它以适应您的设计):

<template name="ImageBanner">
    <img src="/{{ sauce }}" />
    <h5 style="color: {{ getColor }}">Yo</h5>
</template>

Javascript部分。

Template.ImageBanner.onCreated(function() {
    var instance = this;
    instance.color = new ReactiveVar("#000000");
});
Template.ImageBanner.helpers({
    getColor: function() {
        var instance = Template.instance();
        function componentToHex(c) {
            var hex = c.toString(16);
            return hex.length == 1 ? "0" + hex : hex;
        }
        function rgbToHex(r, g, b) {
            return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
        }
        var ct = new ColorThief();
        instance.myImage = new Image;
        instance.myImage.onload = function() {
            var rgb = ct.getColor( instance.myImage );
            instance.color.set( rgbToHex( rgb[0], rgb[1], rgb[2] ) );
        }
        instance.myImage.src = this.sauce;
        return Template.instance().color.get();
    },
});