fabric 右键菜单


import { fabric } from 'fabric';
import { Rect } from './rect';

/**
 * 按钮
 */
export class ContextMenu {
    // 测试调用方法
    copy = 'copy';
    isMenuShow = false;
    isMenuEleShow = false;

    constructor(canvas) {
        // 设置启用右键,禁止默认右键菜单
        canvas.set({
            fireRightClick: true, // 启用右键,button 为 3
            stopContextMenu: true, // 禁止默认右键菜单
        });
        // 添加矩形
        canvas.add(new fabric.Rect(Rect.defaultRect()));
        // 添加菜单
        this.addContextMenu();
        // 绑定鼠标右键
        this.bindMouseClick(canvas);
    }

    /**
     * 添加右键菜单
     */
    addContextMenu(canvas) {
        let self = this;
        let ele = `
            
复制
剪切
删除
上移
下移
置顶
置底
导出选中
导出全部
粘贴
撤销
重做
放大
缩小
导入
导出全部
` $('body').append(ele); // 绑定对应事件 $('.contextMenu-copy').on('click', (e) => { self.doCopy(self); }); } /** * 模拟调用事件 * @param self */ doCopy(self) { console.log(self.copy); } /** * 绑定鼠标点击事件 * @param canvas */ bindMouseClick(canvas) { canvas.on('mouse:down', (e) => { let menuId = 'contextMenu'; let menuEleId = 'contextMenuEle'; if (e.button === 3) { if (e.target) { let activeEle = e.target; this.isMenuEleShow = true; this.showMenu(e, menuEleId); this.isMenuShow && (this.hideMenu(menuId), this.isMenuShow = false); } else { this.isMenuShow = true; this.showMenu(e, menuId); this.isMenuEleShow && (this.hideMenu(menuEleId), this.isMenuEleShow = false); } } else { this.isMenuShow && (this.hideMenu(menuId), this.isMenuShow = false); this.isMenuEleShow && (this.hideMenu(menuEleId), this.isMenuEleShow = false); } }); } /** * 显示菜单 * @param e * @param showId */ showMenu(e, showId) { // 默认 canvas 右键 let menu = $(`#${ showId }`); let menuWidth = menu.width(); let menuHeight = menu.height(); let canvas = $('.upper-canvas'); let canvasWidth = canvas.width(); let canvasHeight = canvas.height(); let pointX = e.pointer.x; let pointY = e.pointer.y; if (canvasWidth - pointX <= menuWidth) { pointX -= menuWidth - 10; } else { pointX += 10; } if (canvasHeight - pointY <= menuHeight) { pointY -= menuHeight - 8; } else { pointY += 12; } menu.css({ top: pointY, // 鼠标指针稍下方 left: pointX, visibility: 'visible', }); } /** * 隐藏菜单 */ hideMenu(showId) { if (showId) { $(`#${ showId }`).css('visibility', 'hidden'); } else { $('#contextMenuEle').css('visibility', 'hidden'); $('#contextMenu').css('visibility', 'hidden'); } } }