fabric 滑鼠動態繪製圖形
阿新 • • 發佈:2022-04-19
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; } }); } }