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


相关推荐
Cobyte13 分钟前
17. Vue3 业务组件库按需加载的实现原理
前端·javascript·vue.js
谢尔登22 分钟前
原型理解从入门到精通
开发语言·javascript·原型模式
粥里有勺糖25 分钟前
视野修炼-技术周刊第127期 | Valdi
前端·javascript·github
码上成长1 小时前
Vue Router 3 升级 4:写法、坑点、兼容一次讲透
前端·javascript·vue.js
qq_398586542 小时前
浏览器中内嵌一个浏览器
前端·javascript·css·css3
*小雪3 小时前
uniapp写H5授权登录及分享,返回到目标页面
开发语言·javascript·uni-app
性野喜悲3 小时前
ts+uniapp小程序时间日期选择框(分开选择)
前端·javascript·vue.js
你不是我我4 小时前
【Java 开发日记】SQL 语句左连接右连接内连接如何使用,区别是什么?
java·javascript·数据库
一壶浊酒..5 小时前
请求签名(Request Signature)
javascript
Cocktail_py7 小时前
JS如何调用wasm
开发语言·javascript·wasm