vue中使用fabric.js
时间: 2025-02-19 08:33:27 浏览: 57
### 集成 Fabric.js 到 Vue 项目
为了在 Vue 项目中集成和使用 Fabric.js 进行画布操作,需遵循特定步骤来确保组件间的良好协作。
#### 安装依赖包
首先,在 Vue 项目环境中安装 `fabric` 库作为开发依赖项。这可以通过 npm 或 yarn 来完成:
```bash
npm install fabric --save
```
或者
```bash
yarn add fabric
```
#### 初始化 Canvas 组件
创建一个新的 Vue 单文件组件用于承载 Fabric.js 的 canvas 实例。在此过程中,引入 fabric 并初始化 canvas 对象[^2]。
```javascript
<template>
<div class="canvas-container">
<canvas id="drawingCanvas"></canvas>
</div>
</template>
<script>
import { fabric } from 'fabric';
export default {
name: "DrawingBoard",
mounted() {
const canvasElement = document.getElementById('drawingCanvas');
this.canvasInstance = new fabric.Canvas(canvasElement);
// 设置画布大小
this.canvasInstance.setDimensions({
width: window.innerWidth,
height: window.innerHeight * 0.8
});
}
};
</script>
<style scoped>
.canvas-container {
position: relative;
}
</style>
```
#### 加载图像到画布上
通过定义方法加载外部 URL 图像至画布内,并允许对其进行交互式编辑如拖拽、旋转等操作[^1]。
```javascript
methods: {
loadImage(url) {
fabric.Image.fromURL(url, img => {
img.scale(0.5).set({ left: 100, top: 100 }).center();
this.canvasInstance.add(img);
});
}
},
mounted() {
...
this.loadImage('http://example.com/image.png'); // 调用此函数以加载图片
}
```
#### 添加鼠标事件监听器支持拖动与缩放
为了让用户能够更方便地操控画布上的对象,还需注册相应的 mouse 和 wheel 事件处理器以便响应用户的输入行为。
```javascript
created() {
this.$nextTick(() => {
let canvas = this.canvasInstance;
// 启用选择模式,默认情况下不允许多选
canvas.selection = false;
// 处理鼠标点击事件
canvas.on('mouse:down', opt => {
var target = opt.target;
if (!target || !this.isDragging) return;
this.selectedObject = target;
this.isDragging = true;
});
// 滚轮滚动时调整视图比例尺
canvas.on('mouse:wheel', function(opt) {
var delta = opt.e.deltaY;
var pointer = canvas.getPointer(opt.e);
if (delta > 0) {
canvas.zoomToPoint(new fabric.Point(pointer.x, pointer.y), canvas.getZoom() / 1.1);
} else if (delta < 0) {
canvas.zoomToPoint(new fabric.Point(pointer.x, pointer.y), canvas.getZoom() * 1.1);
}
opt.e.preventDefault(); //阻止默认浏览器动作
opt.e.stopPropagation(); //停止冒泡
});
})
}
```
阅读全文
相关推荐


















