简体   繁体   中英

Apply filters from an array in CamanJS

I want to store all the filters applied by different buttons and then apply then sequentially on an image. For example, if a user clicks on Brigthness, Noise, Contrast. I want to store these filters and once a user clicks on Apply Filters. I want to apply them all. I tried the following method:

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

But this gives me the error this.filters is not a function . I can use the commented out line but that will only apply predetermined filters. I want to apply filters based on user selection and I want to apply them all at once when user clicks on apply filters.

Here is a link to the library: http://camanjs.com/examples/

Can anyone please guide me how can I achieve what I want? Let me know if I did not explain the question clearly before downvoting.

That error is showing up because when you use this inside foreach the value of this points the filter array and not caman object Try this

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

In above code a copy of this is made which is then passes to inside the loop with name as that

this.filters won't work because 'this' refers to the scope of function(item, index) {...}

I would do something like this:

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

You can define objects in your array and loop over the effects using 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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM