Search code examples
javascripthtml5-canvascamanjs

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.


Solution

  • 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