在聚合物元素加载上选择 img 元素

Selecting an img element on polymer element load

我创建了一个聚合物元素,其中有一个 img 标签。我正在使用 javascript 库 (Vibrant.js),它基本上从图像中拾取主色并给出颜色代码。我正在尝试 select 图像元素 attached 聚合物事件。但不知何故,图像元素没有得到正确的 selected。

我得到以下异常。

Vibrant.min.js:1 Uncaught IndexSizeError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The source width is 0.

<dom-module id="my-image-block">
<template>
    <div class="service-wrapper">
        <div><img id="imgobject" src={{imagepath}}></div>
        <div class="service-wrapper-inner">
            <div>
                <p class="group-title">Stencil
                <p> <!--TODO : Remove hard coding-->
                    <div class="title">
                <p>Some content</p></div>
            <p class="last-modified">Last updated: {{lastmodified}}</p>
        </div>
        <div class="description">
            <p>{{description}}</p>
        </div>
    </div>
    </div>
</template>
<script>
    Polymer({
        is: "my-image-block",
        attached: function () {
            var self = this;
            var imageobject = self.$.imgobject;
            var vibrant = new Vibrant(imageobject, 64, 6);
            var swatches = vibrant.swatches();
            var backColor = swatches["Vibrant"].getHex()
            $(".service-wrapper-inner").css("background-color", backColor);
        }
    });
</script>

可以通过将 widthheight 提供给图像标签来解决您的错误。

<template>
 <style>
  #imgobject{
   width: 100px;
   height: 100px;
  }
 </style>
 <!-- rest of your code -->

但即使在那之后我还是没能做到运行现在我得到了一个新的错误

Vibrant.js:651 Uncaught TypeError: Cannot read property 'map' of undefined

在进一步调试时,我发现此错误是由于 cmap wa coming as false rather than an object as expected. This was happening because when the js disintegrated image and read rgba value of each pixel it got 0 as value, as a result it did not push allpixels 数组中的任何内容而生成的 vibrant 中未处理的错误。

我也尝试使用充满活力的示例中的图像,但没有成功。

我能够通过在 img 对象的 on-load 事件上调用一个函数来做到这一点。

<!-- rest of the code-->
<div><img id="image-object" src={{imagepath}} on-load="handleImageObjectOnLoad"></div>
<!-- rest of the code-->

对于聚合物代码,我做了类似的事情。

<script>
    Polymer({
        is: "marketplace-image-block",
        handleImageObjectOnLoad: function () {
            var self = this;
            var imageobject = self.$['image-object'];
            var vibrant = new Vibrant(imageobject, 64, 5);
            var swatches = vibrant.swatches();
            var backColor = swatches["Vibrant"].getHex();
            self.customStyle["--custom-background-color"] = backColor;
            self.updateStyles();
        }
    });
</script>

其中 --custom-background-color 是 css 样式变量。

<style>
        :host{
            --custom-background-color: grey;
        }
.service-wrapper-inner {
    background-color: var(--custom-background-color);
  }
</style>