fabric.js的使用

安装:npm install fabric --save

javascript 复制代码
// 使用fabric实现:
import { fabric } from 'fabric'


initFabric () {
  // create a wrapper around native canvas element (with id="canvasEl")
  let canvas = new fabric.Canvas('canvasEl')
  // create a rectangle object
  let rect = new fabric.Rect({
    left: 100,
    top: 100,
    fill: 'red',
    width: 20,
    height: 20,
    // angle:45,
  })

  // "add" rectangle onto canvas
  canvas.add(rect)

  // 改变rect的属性,然后重新渲染
  rect.set({ left: 50, top: 50 })
  canvas.renderAll()

  let circle = new fabric.Circle({
    radius: 20,
    fill: 'green',
    left: 100,
    top: 100,
  })
  let triangle = new fabric.Triangle({
    width: 20,
    height: 30,
    fill: 'blue',
    left: 150,
    top: 50,
  })
  canvas.add(circle, triangle)

  // 禁止框选(多选)
  canvas.selection = false // disable group selection
  // 禁止单个选择
  // circle.set('selectable', false); // make object unselectable

  // Path
  let path = new fabric.Path('M 0 0 L 200 100 L 170 200 z')
  // path.set({ left: 120, top: 120 });
  path.set({ fill: 'red', stroke: 'green', strokeWidth: 5, opacity: 0.5 })
  // canvas.add(path);

  // 旋转角度,有动画效果!
  rect.animate('angle', 45, {
    onChange: canvas.renderAll.bind(canvas),
    duration: 4000,
    easing: fabric.util.ease.easeOutBounce
  })
},
javascript 复制代码
// canvas自己实现这些:
initCanvas () {
  let canvasEl = document.getElementById('canvasContainer')
  // 获取上下文:get 2d context to draw on (the "bitmap" mentioned earlier)
  let ctx = canvasEl.getContext('2d')
  // set fill color of context
  ctx.fillStyle = 'red'

  ctx.translate(100, 100) // 位移到指定位置
  ctx.rotate(Math.PI / 180 * 45)  // 旋转角度

  // create rectangle at a 100,100 point, with 20x20 dimensions
  // ctx.fillRect(100,100,20,20)

  ctx.fillRect(-10, -10, 20, 20)
},


相关推荐
摘星小杨1 小时前
如何在前端循环调取接口,实时查询数据
开发语言·前端·javascript
Hilaku1 小时前
从搜索排名到 AI 回答? 先聊一聊 AI 可见度工具 BuildSOM !
前端·javascript·程序员
豹哥学前端2 小时前
前端工程化实战:从包管理到 Vite 配置,一套下来全明白
前端·javascript·vite
干中学_20262 小时前
vue3 画布编辑器「平移」天坑?只需 5 行代码,完美优雅复刻大厂体验!
javascript
大家的林语冰4 小时前
Canvas 文艺复兴,HTML-in-Canvas 炫酷特效摆拍走红,Canvas 中也能渲染交互式的 HTML 元素了
前端·javascript·html
2401_865439636 小时前
CSS中隐藏元素的多重技巧与应用场景
开发语言·前端·javascript
烛衔溟6 小时前
TypeScript 中的类基础
javascript·ubuntu·typescript
mCell6 小时前
从云相册的缩略图说起:Bun.Image 让我告别 sharp
javascript·图片资源·bun
ljt27249606617 小时前
Vue笔记(三)--用户交互
javascript·vue.js·笔记