import { fabric } from 'fabric';
import { Rect } from "./rect";
/**
* 动态拖动鼠标绘制图形
* 滚轮 重置绘图次数
*/
export class DynamicShape {
count = 1;
isDrawing = false;
constructor(canvas) {
// 绑定鼠标动态绘制图形
this.bindDrawEvent(canvas);
// 绑定鼠标滚轮点击,用于重置绘制次数
this.bindMouseClick(canvas);
}
/**
* 绑定鼠标动态绘制图形
* @param canvas
*/
bindDrawEvent(canvas) {
let rect, mouseS, objs = [];
let self = this;
canvas.on('mouse:down', (e) => {
if (self.count) {
self.isDrawing = true;
mouseS = {
mx: e.e.offsetX,
my: e.e.offsetY,
};
rect = new fabric.Rect(Object.assign(Rect.defaultRect(), { left: mouseS.mx, top: mouseS.my, width: 0, height: 0, id: Math.random() }));
objs.push(rect);
// 添加图形至画布
canvas.add(rect);
canvas.renderAll();
}
});
$(document).on('mousemove', (e) => {
if (self.isDrawing && self.count) {
let mouseE = { mx: e.originalEvent.offsetX, my: e.originalEvent.offsetY };
rect.set({ width: mouseE.mx - mouseS.mx, height: mouseE.my - mouseS.my });
canvas.renderAll();
}
});
canvas.on('mouse:up', (e) => {
if (self.isDrawing) {
canvas.discardActiveObject();
// 清空所有选中,只选中绘制图形
canvas.setActiveObject(rect);
canvas.renderAll();
// 重置
self.count = 0;
self.isDrawing = false;
rect = mouseS = null;
objs = [];
}
});
}
/**
* 将执行方法绑定到鼠标右键,以供快速测试功能可用性
*/
bindMouseClick(canvas) {
$('.upper-canvas').on('mousedown', (e) => {
let type = e.originalEvent.which;
switch (type) {
case 1:
// console.log('left');
break;
case 2:
// 重置绘制次数
this.count = 1;
break;
case 3:
// console.log('right');
break;
}
});
}
}