天下无坑

天下无坑


填充的种类 fill

>官方介绍 [Introduction to Fabric.js. Part 2.](http://fabricjs.com/fabric-intro-part-2#gradients "Introduction to Fabric.js. Part 2.")

颜色填充 Color

//投影
const fillColor = async function (text, options = {}) {
  if (typeof text !== 'string' || text === '')
    return null
  const opt = {
    top: 0, left: 0,
    fill: '#000',
    fontSize: 80,
    fontFamily: '华文琥珀',
    ...options
  }
  new fabric.Text(text, opt)
}

渐变色填充 Gradient


const fillGradient = function (text, options = {}) {
  const opt = { ...options }
  const oText = new fabric.Text(text, opt)
  const height = oText.calcTextHeight()
  const width = oText.calcTextWidth()

  const gradient = new fabric.Gradient({
    type: 'linear', // or 'radial'
    gradientUnits: 'pixels', // or 'percentage'
    coords: {
      // r1: 0, r2: 0, // type: 'radial' only have
      x1: opt.left, y1: 0,
      x2: opt.left, y2: height
    },
    colorStops: [
      { offset: 0, color: 'rgb(254, 35, 93)' },
      { offset: 1, color: 'rgb(255, 199, 102)' }
    ]
  })
  oText.set('fill', gradient)
  return oText
}

图案填充 Pattern

> [js 完成对图片的等比例缩放的方法](https://my.oschina.net/u/4297117/blog/4527555 "js 完成对图片的等比例缩放的方法")

> [使用fabric.js缩放画布时,像素完美缩放图像(Pixel perfect scaling of images while zooming the canvas with fabric.js)](https://www.it1352.com/884313.html "使用fabric.js缩放画布时,像素完美缩放图像(Pixel perfect scaling of images while zooming the canvas with fabric.js)")

/** 返回Image对象 */
function asyncImage(src) {
  console.log(src)
  if (!src)
    return null
  return new Promise(resolve => {
    const oImg = new Image()
    // 解决跨域污染问题
    oImg.crossOrigin = 'anonymous'
    oImg.onerror = (res) => {
      resolve(null);
      console.error(res)
    }
    oImg.onload = () => {
      resolve(oImg)
    }
    oImg.src = src
  }
  )
}

//图案填充
const asyncFillPattern = async function (text, options = {}) {
  if (typeof text !== 'string' || text === '')
    return null
  const opt = {
    top: 0, left: 0,
    fill: '#000',
    fontSize: 80,
    fontFamily: '华文琥珀',
    ...options
  }

  const img = await asyncImage('data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAHklEQVQImWNkYGBgYGD4//8/A5wF5SBYyAr+//8PAPOCFO0Q2zq7AAAAAElFTkSuQmCC')
  const pattern = new fabric.Pattern({
    source: img, repeat: 'repeat'
  })
  return new fabric.Text(text, {
    ...opt,
    fill: pattern
  })
}

页面列表

ITEM_HTML