How to apply filter to canvas backgroundImage in F

2019-03-31 05:45发布

Sorry if someone asked the same question. I can't find any way apply filter to canvas backgroundImage.

I tried to do something like here: https://stackoverflow.com/a/13541734/1777335

And my code:

setBackground: function () {
    fabric.Image.fromURL(this.model.get('background'), (function(image){
      this.canvas.setWidth(image.width);
      this.canvas.setHeight(image.height);
      image.filters.push(new fabric.Image.filters.Grayscale());
      image.applyFilters();
      console.log(image);
      this.canvas.backgroundImage = image.getElement();
      this.canvas.renderAll();
    }).bind(this));
  }

Also i tried to do this:

setBackground: function () {    
    this.canvas.setBackgroundImage(this.model.get('background'), (function () {
      this.canvas.backgroundImage();
      this.canvas.setWidth(this.canvas.backgroundImage.naturalWidth);
      this.canvas.setHeight(this.canvas.backgroundImage.naturalHeight);
      this.canvas.backgroundImage.filters = [new fabric.Image.filters.Grayscale()];
      this.canvas.backgroundImage.applyFilters((function(){
        this.canvas.renderAll();
      }).bind(this));
    }).bind(this));
  }

But nothing has changed. Can you help me in this question?

Thanks.

Solved! I'm noob :) Code was almost correct, but i forgot about asynchronous nature of javascript.

setBackground: function () {
    fabric.Image.fromURL(this.model.get('background'), (function(image){
      this.canvas.setWidth(image.width);
      this.canvas.setHeight(image.height);
      image.filters.push(new fabric.Image.filters.Grayscale(30));
      image.filters.push(new fabric.Image.filters.Brightness(90));
      image.applyFilters((function(){
        this.canvas.backgroundImage = image.getElement();
        this.canvas.renderAll();
      }).bind(this));
    }).bind(this));
  }

标签: fabricjs
0条回答
登录 后发表回答