作者GitHub:https://github.com/gitboyzcf 有兴趣可关注
Vue3代码,Vue2相似改吧改吧
前言
Fabric.js
Fabric.js(英文官网)是一个强大而简单的 Javascript HTML5画布库(也就是针对canvas进行的封装操作,使用起来更方便)
Fabric在画布元素的顶部提供交互式对象模型、Fabric还具有SVG到画布(以及画布到SVG)解析器
安装
npm install fabric --save
or
pnpm install fabric --save
or
yarn add fabric --save
实现
Demo.vue
<script setup>
import { fabric } from 'fabric'
let canvas = null // 画布实例
let currentPolyline = null // 临时折线
let points = []
// 初始化画布
const init = () => {
canvas = new fabric.Canvas('c')
canvas.selectionColor = 'transparent'
canvas.selectionBorderColor = 'transparent'
canvas.skipTargetFind = true // 禁止选中
canvas.on('mouse:down', canvasMouseDown) // 鼠标在画布上按下
canvas.on('mouse:move', canvasMouseMove) // 鼠标在画布上移动
canvas.on('mouse:dblclick', canvasMouseDblclick) // 鼠标在画布上双击
}
// 创建折线
const createPolyline = (e) => {
const currentPoint = e.absolutePointer
currentPolyline = new fabric.Polyline(
[
{ x: currentPoint.x, y: currentPoint.y },
{ x: currentPoint.x, y: currentPoint.y }
],
{
fill: 'transparent',
stroke: 'red',
objectCaching: false
}
)
canvas.add(currentPolyline)
}
// 修改当前正在创建的折线
const changeCurrentPolyline = (e) => {
const currentPoint = e.absolutePointer
let points = currentPolyline.points
points.push({
x: currentPoint.x,
y: currentPoint.y
})
canvas.requestRenderAll()
}
// 折线橡皮带
const changePolylineBelt = (e) => {
const currentPoint = e.absolutePointer
let points = currentPolyline.points
points[points.length - 1].x = currentPoint.x
points[points.length - 1].y = currentPoint.y
canvas.requestRenderAll()
}
// 完成折线绘制
const finishPolyline = (e) => {
const currentPoint = e.absolutePointer
let points = currentPolyline.points
points[points.length - 1].x = currentPoint.x
points[points.length - 1].y = currentPoint.y
points.pop()
points.pop()
// 按需添加自闭合代码
// if (points[0].x != points[points.length - 1].x && points[0].y != points[points.length - 1].y) {
// changeCurrentPolyline({ absolutePointer: { x: points[0].x, y: points[0].y } })
// }
canvas.remove(currentPolyline)
if (points.length > 1) {
let polyline = new fabric.Polyline(points, {
stroke: 'red',
fill: 'transparent'
})
canvas.add(polyline)
}
currentPolyline = null
canvas.requestRenderAll()
}
// 鼠标在画布上按下
const canvasMouseDown = (e) => {
if (currentPolyline === null) {
createPolyline(e)
} else {
changeCurrentPolyline(e)
}
}
// 鼠标在画布上移动
const canvasMouseMove = (e) => {
if (currentPolyline) {
changePolylineBelt(e)
}
}
// 鼠标在画布上双击
const canvasMouseDblclick = (e) => {
finishPolyline(e)
}
onMounted(() => {
init()
})
</script>
<template>
<div>
<canvas id="c" width="500" height="470" style="border: 1px solid #ccc"></canvas>
</div>
</template>
到这里就结束了,后续还会更新 前端 系列相关,还请持续关注!
感谢阅读,若有错误可以在下方评论区留言哦!!!