从Camanjs的阵列中应用过滤器



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

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/

任何人都可以指导我如何实现自己想要的东西?让我知道我是否在投票之前没有清楚地解释这个问题。

该错误正在显示,因为当您在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

的名称将其传递到内部循环内部。

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

您可以在数组中定义对象,并使用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();
});

最新更新