Fabric.js 是一个功能强大且操作简单的 Javascript HTML5 canvas 工具库。
安装
npm i fabric --save
引入
import { fabric } from 'fabric'
创建 canvas 容器
<canvas width="400" height="400" id="c" style="border: 1px solid #ccc;"></canvas>
基础图形
1.矩形
<template>
<canvas width="400" height="375" id="canvas" style="border: 1px solid #ccc;"></canvas>
</template>
<script setup>
import { onMounted } from 'vue'
import { fabric } from 'fabric'
function init() {
const canvas = new fabric.Canvas('canvas') // 绑定canvas,传入id
const rect = new fabric.Rect({
top: 100, // 距离容器顶部 100px
left: 100, // 距离容器左侧 100px
fill: 'orange', // 填充 橙色
width: 100, // 宽度 100px
height: 100 // 高度 100px
})
// 将矩形添加到画布中
canvas.add(rect)
}
onMounted(() => {
init()
})
</script>
2.圆角矩形
<template>
<canvas width="400" height="375" id="canvas" style="border: 1px solid #ccc;"></canvas>
</template>
<script setup>
import { onMounted } from 'vue'
import { fabric } from 'fabric'
function init() {
const canvas = new fabric.Canvas('canvas') // 绑定canvas,传入id
const rect = new fabric.Rect({
top: 100, // 距离容器顶部 100px
left: 100, // 距离容器左侧 100px
fill: 'orange', // 填充 橙色
width: 100, // 宽度 100px
height: 100, // 高度 100px
rx: 20, // x轴的半径
ry: 20 // y轴的半径
})
// 将矩形添加到画布中
canvas.add(rect)
}
onMounted(() => {
init()
})
</script>
3.圆形
<template>
<canvas width="400" height="375" id="canvas" style="border: 1px solid #ccc;"></canvas>
</template>
<script setup>
import { onMounted } from 'vue'
import { fabric } from 'fabric'
function init() {
const canvas = new fabric.Canvas('canvas')
const circle = new fabric.Circle({
top: 100,
left: 100,
radius: 50, // 圆的半径 50
fill: 'green'
})
canvas.add(circle)
}
onMounted(() => {
init()
})
</script>
4.椭圆形
<template>
<canvas width="400" height="375" id="canvas" style="border: 1px solid #ccc;"></canvas>
</template>
<script setup>
import { onMounted } from 'vue'
import { fabric } from 'fabric'
function init() {
const canvas = new fabric.Canvas('canvas')
const ellipse = new fabric.Ellipse({
top: 20,
left: 20,
rx: 70,
ry: 30,
fill: 'hotpink'
})
canvas.add(ellipse)
}
onMounted(() => {
init()
})
</script>
和圆形不同,椭圆不需要设置 radius ,但要设置 rx 和 ry。
当 rx > ry :椭圆是横着的
当 rx < ry:椭圆是竖着的
当 rx = ry: 看上去就是个圆形
5.多边形
<template>
<canvas width="400" height="375" id="canvas" style="border: 1px solid #ccc;"></canvas>
</template>
<script setup>
import { onMounted } from 'vue'
import { fabric } from 'fabric'
function init() {
const canvas = new fabric.Canvas('canvas')
const polygon = new fabric.Polygon([
{x: 30, y: 30},
{x: 150, y: 140},
{x: 240, y: 150},
{x: 100, y: 30}
], {
fill: '#ffd3b6', // 填充色
stroke: '#6639a6', // 线段颜色:紫色
strokeWidth: 5 // 线段粗细 5
})
canvas.add(polygon)
}
onMounted(() => {
init()
})
</script>
Fabric.js相关API
更详细的用法可以参考:https://juejin.cn/post/7026941253845516324#heading-26