Ali Parr
Ali Parr

Reputation: 4787

Text color overlay in FabricJS

I am trying to create an effect in FabricJS, where the color of some text I am adding to my canvas is determined by a texture. Should be easy, but when I apply the texture as a pattern, I cannot work out the combination of scale, rotation etc that I need to make it work. It appears to me like the pattern is being applied 'local' to the object, so (0,0), is the object's top left coords, rather than that of the overall image.

So if here's my text color texture,

enter image description here

and I placed some text in the middle, the effect I want would be this:

enter image description here

I've tried various things with static canvas etc, but I've hit a dead end. Please can someone help? Here's my current attempt:

var patternSourceCanvas = new fabric.StaticCanvas();

    oImg.setAngle(-angles[i]);

    patternSourceCanvas.add(oImg);

    var pattern = new fabric.Pattern({
      source: function() {

       patternSourceCanvas.setDimensions({
          width: oImg.getWidth(),
          height: oImg.getHeight()
        });

        return patternSourceCanvas.getElement();
      },
      repeat: 'no-repeat'
    });


    var text = new fabric.Text(entry, {
      originX: 'center',
      originY: 'center',
      left: (coords[i][0] * bufWidth),
      top: (coords[i][1] * bufHeight),
      fill: pattern,
      centeredRotation: true,
      angle: angles[i],
      fontFamily: 'Kapra',
      fontSize: 42
    });

Huge thanks in advance!

Upvotes: 2

Views: 2438

Answers (1)

AndreaBogazzi
AndreaBogazzi

Reputation: 14731

i got this idea, you can obtain the effect using the globalCompositeOperation property of fabricJs objects

enter image description here

// clear canvas
canvas.clear();

    var text = new fabric.Text('AAAAA', {
      originX: 'center',
      originY: 'center',
      left:30,
      top: 30,
      fill: 'rgba(0,0,0,1)',
      centeredRotation: true,
      angle: 20,
      fontSize: 100,
    });
canvas.add(text);
fabric.Image.fromURL('../assets/pug.jpg', function(oImg) { 
  oImg.globalCompositeOperation = 'source-atop';
  oImg.width = canvas.width;
  oImg.heigth = canvas.height;
  canvas.add(oImg);
  var rect = new fabric.Rect({
    width: 200,
    height: 200,
    globalCompositeOperation: 'destination-over',
    fill: 'black'
  });
  canvas.add(rect);   
});

So basically you render the text in any color, black. Then you render the color image OVER the text, covering all the canvas, specifying globalCompositeOperation = 'source-atop'

After this you have a colored text on a white background. To have a black background now draw a rect big as the canvas, but specify globalCompositeOperation = 'destination-over'

So you will do something totally different but it will work. May need tweaking and may not fit your needs. But it should show the example you posted.

Upvotes: 2

Related Questions