3. Fabric 基本使用

1. 画正方形

  let canvas = new fabric.Canvas('canvas', { backgroundColor: 'grey' })
  // 画正方形
  let rect = new fabric.Rect({
    left: 100,
    top: 100,
    fill: 'red',
    width: 20,
    height: 20,
    angle: 45
  })

canvas.add(rect)

2. 画圆

  let canvas = new fabric.Canvas('canvas', { backgroundColor: 'grey' })
  // 画圆
  let circle = new fabric.Circle({
    left: 100,
    top: 100,
    fill: 'green',
    width: 20,
    height: 20,
    radius: 20
  })

canvas.add(circle)

3. 画三角形

  let canvas = new fabric.Canvas('canvas', { backgroundColor: 'grey' })
  // 画三角形
  let triangle = new fabric.Triangle({
    width: 20,
    height: 30,
    fill: 'blue',
    left: 50,
    top: 50
  })

canvas.add(triangle)

4. 画椭圆

  let canvas = new fabric.Canvas('canvas', { backgroundColor: 'grey' })
  // 画椭圆
  let ellipse = new fabric.Ellipse({
    rx: 20,
    ry: 30,
    left: 200,
    top: 200,
    fill: '#87ceed'
  })

canvas.add(ellipse)

5. 画线

  let canvas = new fabric.Canvas('canvas', { backgroundColor: 'grey' })
  // 画线
  let line = new fabric.Line([70, 100, 150, 200], {
    stroke: 'blue'
  })

canvas.add(line)

6. 画多边形

  let canvas = new fabric.Canvas('canvas', { backgroundColor: 'grey' })
  // 画六边形
  let hexagon = new fabric.Polygon(
    [
      {
        x: 50,
        y: 0
      },
      {
        x: 25,
        y: 43.3
      },
      {
        x: -25,
        y: 43.301
      },
      {
        x: -50,
        y: 0
      },
      {
        x: -25,
        y: -43.301
      },
      {
        x: 25,
        y: -43.301
      }
    ],
    {
      stroke: 'red',
      left: 0,
      top: 0,
      strokeWidth: 2,
      strokeLineJoin: 'bevel'
    }
  )

canvas.add(hexagon)

7. 添加图片和过滤器

  let canvas = new fabric.Canvas('canvas', { backgroundColor: 'grey' })
  // 添加图片
   let img = new Image()
   img.src = 'src/views/Fabric/1.jpg'
   img.addEventListener('load', () => {
     const imgInstance = new fabric.FabricImage(img, {
       // 设置图片位置和样子
       left: 0,
       top: 0,
       angle: 0 // 设置图形顺时针旋转角度
     })

     // 添加过滤器
     imgInstance.filters.push(new fabric.filters.Sepia())
     // 应用过滤器并在完成后重新渲染画布
     imgInstance.applyFilters()
     canvas.add(imgInstance) // 加入到canvas中
   })

canvas.add(img)

8. 添加文本和动画

  let canvas = new fabric.Canvas('canvas', { backgroundColor: 'grey' })
    // 添加文本
  let text = new fabric.FabricText('hello world', { left: 100, top: 100 })
  canvas.add(text)

  let fn = (opt) => {
    console.log(opt)
  }
  text.on('mousedown', fn)

  text.animate(
    {
      left: 300,
      top: 200,
      fontSize: 48,
      fill: 'blue'
    },
    {
      duration: 2000, // 设置动画的持续时间为 2000 毫秒
      onChange: canvas.renderAll.bind(canvas), // 在动画过程中更新 canvas
      easing: fabric.util.ease.easeInQuad,
      onComplete: () => {
        console.log(1111)
      }
    }
  )

canvas.add(text)

你可能感兴趣的:(Fabric,fabric,前端,javascript)