Fabricjs-new fabric.Pattern填充模板

(function() {
  var canvas = this.__canvas = new fabric.Canvas('c');
  fabric.Object.prototype.transparentCorners = false

  function loadPattern(url) { //传入图片地址
    fabric.util.loadImage(url, function(img) { //加载图片
      text.set('fill', new fabric.Pattern({ //将图片设置为填充模板 文本填充
        source: img,
        repeat: document.getElementById('repeat').value //repeat repeat-x repeat-y no-repeat
      }));
      shape.set('fill', new fabric.Pattern({ //图形填充
        source: img,
        repeat: document.getElementById('repeat').value
      }));
      canvas.renderAll()
    })
  }
  var text = new fabric.Text('Honey,\nI\'m subtle', {
    fontSize: 250,
    left: 0,
    top: 0,
    lineHeight: 1,
    originX: 'left',
    fontFamily: 'Helvetica',
    fontWeight: 'bold',
    statefullCache: true,
    scaleX: 0.4,
    scaleY: 0.4
  })
  var shape = new fabric.Rect({
    width: 200,
    height: 100,
    left: 0,
    top: 300
  });
  canvas.add(text, shape)
  loadPattern('./assets/1.jpg')
  document.getElementById('patterns').onchange = function() {
    loadPattern('./assets/' + this.value) //填充不同的模板图片
  }
  document.getElementById('repeat').onchange = function() {
    text.fill.repeat = this.value //这样可以更改填充类型
    canvas.renderAll()
  }
})()

 

posted @ 2022-04-06 16:40  聂小恶  阅读(598)  评论(0编辑  收藏  举报