简体   繁体   中英

How to set background image to text object in Fabric.js canvas

I searched lot but have not found any solution to add background image to Fabric text object on fabric canvas.

Ref: http://fabricjs.com/docs/

You need to use fabric's Pattern object and set it as the fill attribute of your text object to achieve that.

Here's an example code to do that:

var text = new fabric.Text('Your Text', {
    fontSize: 250,
    left: 50,
    top: 0,
    lineHeight: 1,
    originX: 'left',
    fontFamily: 'Helvetica',
    fontWeight: 'bold'
  });
canvas.add(text);

function textBackground(url) {
    fabric.util.loadImage(url, function(img) {
      text.fill = new fabric.Pattern({
        source: img,
        repeat: 'repeat' // repeat, repeat-x, repeat-y or no-repeat
      });
      canvas.renderAll();
    });
}

textBackground('SOMEIMAGE.png');

There's a demo on fabricjs site on this: Patterns Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM