【问题标题】:Apply filters from an array in CamanJS在 CamanJS 中应用数组中的过滤器
【发布时间】:2016-12-11 04:21:58
【问题描述】:

我想存储由不同按钮应用的所有过滤器,然后依次应用到图像上。例如,如果用户单击亮度、噪声、对比度。我想存储这些过滤器,一旦用户点击应用过滤器。我想全部应用它们。我尝试了以下方法:

Caman('#canvas', img, function () {
     //this.brightness(10).render();
     var filters = ["brightness(10)", "noise(20)"];
     filters.forEach(function (item, index) {
          this.filters(item);
     });
     this.render();
});

但这给了我错误this.filters is not a function。我可以使用注释掉的行,但这只会应用预定的过滤器。我想根据用户选择应用过滤器,并且我想在用户点击应用过滤器时一次性应用所有过滤器。

这是图书馆的链接:http://camanjs.com/examples/

谁能指导我如何实现我想要的?如果我在否决之前没有清楚地解释问题,请告诉我。

【问题讨论】:

    标签: javascript html5-canvas camanjs


    【解决方案1】:

    出现该错误是因为当您在 foreach 内使用 this 时,this 的值指向过滤器数组而不是 caman 对象试试这个

    Caman('#canvas', img, function () {
         //this.brightness(10).render();
         var that = this;
         var filters = ["brightness(10)", "noise(20)"];
         filters.forEach(function (item, index) {
            eval('that.'+item); 
         });
         this.render();
    });
    

    在上面的代码中,复制了this,然后将其传递到循环内部,名称为that

    【讨论】:

    • 感谢新手,这似乎是应用过滤器的最简单方法。与其他答案相比,这种方法有什么缺点吗?
    • 没有缺点,虽然你不应该在常见的情况下使用 eval,但是在前端的情况下,当你想要在不影响代码简洁性的情况下进行动态函数调用时,它是完全没问题的小sn-p
    【解决方案2】:

    this.filters 不起作用,因为“this”指的是function(item, index) {...} 的范围

    我会这样做:

    Caman('#canvas', img, function () {
         // make 'this' available in the scope through 'self' variable
         var self = this;      
    
         // Filters must hold the function and not a string of the function.
         // so something like:
         var filters = [
           function() { self.brightness(10); },
           function() { self.noise(20); }
         ];
    
         filters.forEach(function (fn) {
              fn(); // this will execute the anonymous functions in the filters array
         });
    
         this.render();
    });
    

    【讨论】:

      【解决方案3】:

      您可以在数组中定义对象并使用forEach() 循环遍历效果:

      Caman('#canvas', img, function () {
        var filters = [
          { name: "brightness", val:10 },
          { name: "noise", val:20 }
        ];
        var that = this;
        filters.forEach(function(effect) {
          that[effect.name](effect.val);
        });
        this.render();
      });
      

      【讨论】:

      • 当我尝试这个方法时,我得到了错误Uncaught TypeError: that[effect.name] is not a function。我尝试在that 之后添加.,但随后出现关于意外[ 的错误。
      • 确保effectitem 变量重命名)作为参数传递给匿名函数。或者用可测试的代码制作一个 jsfiddle。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-26
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多