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)
},


相关推荐
27669582927 分钟前
携程旅行 token1005
java·linux·前端·javascript·携程旅行·token1005·携程酒店
颜酱32 分钟前
从 DeepSeek 文本对话到流式输出
前端·javascript·人工智能
鬣主任1 小时前
重生之我上班学React----360档案篇。
javascript·react.js
27669582921 小时前
token1005 算法分析
java·前端·javascript·token·token1005·携程酒店·token算法分析
kilito_011 小时前
vue官网例子 讲解2
前端·javascript·vue.js
蜡台1 小时前
Vue实现动态路由
前端·javascript·vue.js·router
sudo_jin2 小时前
从“谁调用指向谁”到“手写Bind源码”,彻底搞懂JavaScript的this机制
前端·javascript
cc_heart2 小时前
antdv-next/x:面向 Vue 的 AI 组件体系
前端·javascript·vue.js
竹林8182 小时前
RainbowKit快速集成多链钱包连接:从“一键连接”到“多链切换”的实战踩坑
前端·javascript
软弹2 小时前
快速了解前端中的跨域问题
前端·javascript·vue.js·react.js·node.js·跨域