How to apply filter to canvas backgroundImage in Fabric.js

北城余情 提交于 2019-12-05 03:24:56

问题


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

来源:https://stackoverflow.com/questions/20119527/how-to-apply-filter-to-canvas-backgroundimage-in-fabric-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!