Fabric.js BlendColor Image Filter

2019-08-13 09:27发布

问题:

I am having trouble changing the color of a small png on the canvas in Fabric.js.

In my research, I found that I could use new fabric.Image.filters.Tint() to modify the color of an image in the way that I was looking to. However, there is no Tint() constructor in v2 of Fabric. According to this page, Tint() is now part of the BlendColor() filter. I have tried various things with BlendColor(), but I have yet to get it to work. Any advice on how to use BlendColor() or some other filter to accomplish what I want is much appreciated.

My best guess is to do something like this, but it doesn't work:

var filter = new fabric.Image.filters.BlendColor({
 color: '#c9f364',
 mode: 'multiply'
});

canvas.getObjects()[0].filters.push(filter);
canvas.getObjects()[0].applyFilters();
canvas.renderAll();

回答1:

set mode:'tint' to BlendColor filter.

var filter = new fabric.Image.filters.BlendColor({
  color: 'red',
  mode: 'tint',
  alpha: 0.5
});

DEMO

var canvas = new fabric.Canvas('c');
fabric.Image.fromURL('http://fabricjs.com/assets/pug.jpg',function(img){
  img.set({
   scaleX:0.3,
   scaleY:0.3
  })
  canvas.add(img);
  var filter = new fabric.Image.filters.BlendColor({
   color:'red',
   mode: 'tint',
   alpha: 0.5
  });
  img.filters.push(filter);
  img.applyFilters();
  canvas.renderAll();
},{
 crossOrigin:'null'
})
canvas{
 border:2px solid #000;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id='c' width=400 height=400></canvas>