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


相关推荐
小约翰仓鼠3 小时前
vue3子组件获取并修改父组件的值
前端·javascript·vue.js
烛阴3 小时前
bignumber.js深度解析:驾驭任意精度计算的终极武器
前端·javascript·后端
你的人类朋友4 小时前
✍️Node.js CMS框架概述:Directus与Strapi详解
javascript·后端·node.js
啊~哈4 小时前
vue3+elementplus表格表头加图标及文字提示
前端·javascript·vue.js
xiaogg36784 小时前
vue+elementui 网站首页顶部菜单上下布局
javascript·vue.js·elementui
weixin_527550404 小时前
初级程序员入门指南
javascript·python·算法
钡铼技术ARM工业边缘计算机5 小时前
千元级PLC平台支持梯形图+Python双开发
javascript
高山我梦口香糖5 小时前
[electron]预脚本不显示内联script
前端·javascript·electron
拉不动的猪7 小时前
安卓和ios小程序开发中的兼容性问题举例
前端·javascript·面试
贩卖纯净水.7 小时前
浏览器兼容-polyfill-本地服务-优化
开发语言·前端·javascript