Fabric.js物件填充背景 Pattern

2018-11-28 13:10:20
2365次阅读
0个评论

Fabricjs 可以将图片设定為其他物件的填充色,今天就来介绍一些帮物件填入图片的方法。


Object.setPatternFill

透过使用物件的 setPatternFill 方法来操作填充背景。
ex:

fabric.util.loadImage('https://www.pakutaso.com/shared/img/thumb/KAZTDSCF2521_TP_V4.jpg', function (img) {
  text.setPatternFill({
      source: img,
      repeat: 'repeat'
  })
  canvas.renderAll()
})

fabric.Pattern

透过使用 fabric.Pattern 类别来创造 pattern 物件,
并且将物件的 fill 属性设定為 pattern。

来个范例:

// 载入图片取得 HTMLelement
fabric.util.loadImage('https://www.pakutaso.com/shared/img/thumb/KAZTDSCF2521_TP_V4.jpg', function (img) {
  // 新增一个 pattern 物件
  const pattern = new fabric.Pattern({
    source: img,
    repeat: 'repeat'
  })
  // 将图片的 fill 属性设定成某个 pattern
  const text = new fabric.Text('铁人赛\n倒数两天', {
    fontSize: 100,
    fontWeight: 800,
    fill: pattern // 设為 pattern
  })
  canvas.add(text)
})

其中 source 必须為 HTMLImageElement 也就是 html 的 img,repeat 模式分几种:

repeat 重复模式,若图片小於物件则会重复自动填满整个物件。
repeat-y 只有上下重复
repeat-x 只有水平重复
no-repeat 不重复
不过目前我们的图片都比我们的填满目标物件还要大,要怎麼去缩小原始的背景图片以便当成重复的背景呢。

动态改变图片

要做到这样的需求,必须要先建立一个 StaticCanvas 来做為一个要当成重复背景的原图,并动态的改变他的大小,最后再输出成 HTMLElement 来做 source 使用。


fabric.util.loadImage('https://www.pakutaso.com/shared/img/thumb/PPH_seiarupusukiku_TP_V4.jpg', function (img) {
  const oImg = new fabric.Image(img)
  // 新增一个新的静态画布
  oImg.scaleToHeight(50) // 缩小成 height = 50
  const patternSourceCanvas = new fabric.StaticCanvas()
  patternSourceCanvas.add(oImg)
  patternSourceCanvas.renderAll()
  const pattern = new fabric.Pattern({
    source: function() {
      // 设定静态画布的大小同等图片大小
      patternSourceCanvas.setDimensions({
        width: oImg.getScaledWidth(),
        height: oImg.getScaledHeight()
      })
      patternSourceCanvas.renderAll()
      // 回传 htmlElement
      return patternSourceCanvas.getElement()
    },
    repeat: 'repeat'
  })
  const text = new fabric.Text('铁人赛\n倒数两天', {
    fontSize: 100,
    fontWeight: 800,
    fill: pattern
  })
  canvas.add(text)
  const rect = new fabric.Rect({
    width: 300,
    height: 200,
    top: 250,
    fill: pattern
  })
  canvas.add(rect)
})

结果

这样一来也可以看到其他 repeat 效果的结果囉。

repeat-x



repeat-y



no-repeat



今日小结

介绍了 Fabricjs pattern 的使用。
可以透过使用 object.setPatternFill() 或是物件属性 fill: pattern 来為物件加入填充背景。
收藏00

登录 后评论。没有帐号? 注册 一个。