流星和彩色小偷赢得了#39;一起工作

时间:2015-06-07 17:12:35

标签: javascript jquery meteor

我一直在使用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>

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

在之前显示的htlm片段之后的html模板中,我一直以这种方式使用彩色小偷:

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

专辑的列表显示正确的颜色小偷无论我做什么似乎都无法工作,我可能会想,如果Meteor有什么东西我不知道。另请注意,Color-Thief.j和Quantize.js包含在客户端文件夹中。

谢谢你们

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

    Template.albumItem.helpers({

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

});

以这种方式在模板albumItem中使用颜色:

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

仍然没有工作,但我确信这是朝着正确的方向迈进,也许现在我们需要弄清楚如何知道这个模板在图片加载后开始...

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我使用以下代码进行此操作。

{{#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();
    },
});