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


相关推荐
Mintopia4 分钟前
计算机图形学漫游:从像素到游戏引擎的奇幻之旅
前端·javascript·计算机图形学
Tina_晴32 分钟前
【基础篇】Promise初体验+案例分析(上)
前端·javascript·面试
7ayl33 分钟前
闭包
javascript
断竿散人34 分钟前
浏览器 History 对象完全指南:从 API 原理到 SPA 路由实战
前端·javascript·vue-router
姜太小白41 分钟前
【ECharts】多个ECharts版本共存解决方案
前端·javascript·echarts
前端风云志44 分钟前
JavaScript面试题,为什么[] + 0 = '0', 而{} + 0 = 0?
javascript
FogLetter1 小时前
节流(Throttle):给频繁触发的事件装上"冷却时间"
前端·javascript
小公主1 小时前
彻底搞懂 Event Loop!这篇文章帮你一次性吃透宏任务、微任务、执行顺序
前端·javascript
EndingCoder1 小时前
排序算法与前端交互优化
开发语言·前端·javascript·算法·排序算法·交互
晓13131 小时前
JavaScript加强篇——第五章 DOM节点(加强)与BOM
java·开发语言·javascript