当前位置:网站首页>Fabric. JS right click menu
Fabric. JS right click menu
2022-07-02 05:17:00 【Director of Moral Education Department】
Brief introduction
Fabric.js Default No Right mouse button event , Only Click the mouse button 、 Mouse button up 、 Mouse movement Other events . But you may need to use... In your work “ Right click ” event , such as “ Right-click menu ” . So there is this article .
<br>
This article focuses on Fabric.js The main api Yes :
fireRightClick: Allow right clickingstopContextMenu: Disable the default right-click menumouse:down: Mouse click event
<br>

<br>
If you don't know Fabric.js Classmate , You can see 《Fabric.js From the beginning to ___》
<br>
This case is developed in a native way , Not based on Vue 、React Other framework , So don't worry too much about the running environment and other problems .
<br>
The case code is placed at the end of the text ~
<br> <br>
Environment and version
Chrome Browser version :96.0.4664.45
Fabric.js edition :4.6.0
<br><br>
Ideas
Let's talk about the needs first :
- Right click the element , Pop up menu ;
- Pop up menu sub 4 In this case ( The menu is on the right side of the mouse , The menu is on the left side of the mouse , The menu is above the mouse , The menu is under the mouse );
- Left click elsewhere on the canvas , The hidden menu ;
<br>
Realize the idea :
- Create a canvas ;
- establish “ menu ” Of DOM Elements ;
- Go to the official website to find “ Right click related events ”;
- Right click on the element , According to the distance between the mouse and the edge of the canvas , Calculate where the menu is to be displayed ;
- Left click on the canvas , The hidden menu ;
<br> <br>
Realization
Look up the documents
In the above idea , In fact, the only difficulty is “ Right click related events ” .

stay Object related documents in , There seems to be no right button for the mouse event , What is slightly touched is the mouse click ( Here I choose mousedown).
<br>
So I went to Document on canvas I looked in the , Find these two properties :
fireRightClick: Whether the canvas can trigger the right-click eventstopContextMenu: Disable the default right-click menu
Ha ha ha ha , Developed ~

<br>
After my careful observation , Find out mouse:down There was a in the incident button attribute :
- left-click :
buttonThe value of is 1 - Right click :
buttonThe value of is 3 - In the key ( That is, click the scroll wheel ),
buttonThe value of is 2, The premise needs to be setfireMiddleClick: true
<br>
Hands on Development
Layout
<style> /* Containers , Relative positioning */ .box { position: relative; } /* canvas , Give me a border */ #canvas { border: 1px solid #ccc; } /* menu */ .menu-x { visibility: hidden; /* The hidden menu */ z-index: -100; position: absolute; top: 0; left: 0; box-sizing: border-box; border-radius: 4px; box-shadow: 0 0 4px rgba(0, 0, 0, 0.3); background-color: #fff; } /* Menu each option */ .menu-li { box-sizing: border-box; padding: 4px 8px; border-bottom: 1px solid #ccc; cursor: pointer; } /* Mouse over options , Change the background color */ .menu-li:hover { background-color: antiquewhite; } /* First option , The top two corners are rounded */ .menu-li:first-child { border-top-left-radius: 4px; border-top-right-radius: 4px; } /* The last option , The bottom two corners are rounded , No border at the bottom */ .menu-li:last-child { border-bottom: none; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; }</style><!-- Containers ( Relative positioning ) --><div class="box"> <!-- canvas --> <canvas id="canvas" width="600" height="600"></canvas> <!-- Right-click menu ( Absolute positioning , And the default is hidden ) --> <div id="menu" class="menu-x" > <div class="menu-li"> Don't do anything? </div> <div class="menu-li"> Don't do anything? </div> <div class="menu-li"> Don't do anything? </div> <div class="menu-li"> Don't do anything? </div> <div class="menu-li" onclick="delEl()"> Delete </div> </div></div>
The effect at this time is shown in the figure above .
<br>
Initialize canvas , And generate graphics
<script>// After the document is loaded, execute window.onload = function() { // Output current fabric edition console.log(`Facrib.js edition :${fabric.version}`) // Initialize canvas init() // Disable the default right-click event on the menu menu.oncontextmenu = function(e) { e.preventDefault() }}// initialization function init() { canvas = new fabric.Canvas('canvas', { fireRightClick: true, // Enable right click ,button The number of 3 stopContextMenu: true, // Disable the default right-click menu }) // rectangular const rect1 = new fabric.Rect({ left: 10, top: 510, fill: 'orange', width: 40, height: 40 }) // Rounded rectangle const rect2 = new fabric.Rect({ left: 510, top: 10, fill: 'pink', width: 40, height: 40, rx: 10, // Round corners x ry: 10, // Round corners y }) // circular const circle = new fabric.Circle({ radius: 30, // radius fill: 'green', left: 20, top: 20, }) // triangle let triangle = new fabric.Triangle({ width: 80, // Bottom edge width height: 100, // The distance from the bottom edge to the fixed point fill: 'blue', left: 500, top: 480 }) // Add rectangle to canvas canvas.add(rect1, rect2, circle, triangle)}</script>
<br>
Add click event ( Judgment right button )
<script>// Omit some of the above code function init() { // Omitted code ...... // Add rectangle to canvas canvas.add(rect1, rect2, circle, triangle) // Press mouse canvas.on('mouse:down', canvasOnMouseDown)} // Click event of mouse on canvas function canvasOnMouseDown(opt) { // Judge : Right click , And right click on the element // opt.button: 1- left-click ;2- In the key ;3- Right click // Click... On the canvas :opt.target by null if (opt.button === 3 && opt.target) { // Get current element activeEl = opt.target menu.domReady = function() { console.log(123) } // Show menu , Set the position of the right-click menu // Get the width and height of the menu component const menuWidth = menu.offsetWidth const menuHeight = menu.offsetHeight // Current mouse position let pointX = opt.pointer.x let pointY = opt.pointer.y // Calculate where the menu appears // If the mouse is close to the right side of the canvas , The menu appears to the left of the mouse pointer if (canvas.width - pointX <= menuWidth) { pointX -= menuWidth } // If the mouse is near the bottom of the canvas , The menu appears just above the mouse pointer if (canvas.height - pointY <= menuHeight) { pointY -= menuHeight } // Show the menu menu.style = ` visibility: visible; left: ${pointX}px; top: ${pointY}px; z-index: 100; ` } else { hiddenMenu() }}// The hidden menu function hiddenMenu() { menu.style = ` visibility: hidden; left: 0; top: 0; z-index: -100; ` activeEl = null}// Remove elements function delEl() { canvas.remove(activeEl) hiddenMenu()}</script>
<br>
In the above code , adopt opt.target Is it null To determine the currently clicked object .
opt.target === null , Just click on the canvas ( No click on graphic elements ).
If your project requirement is to right-click the canvas to display different menus , You can modify the judgment of the above code .
<br><br>
Code warehouse
- Native way to achieve Fabric Right-click menu
- stay Vue3 Use in Fabric Realize the right-click menu function
<br><br>
recommend
《Fabric.js From entry to expansion 》
《Fabric.js Gradient effect ( Including radial gradient )》
<br> <br>
If the content of this article is helpful to you , Please also give me a compliment ~
give the thumbs-up + Focus on + Collection = Learned to
边栏推荐
- The El cascader echo only selects the questions that are not displayed
- Gee series: unit 9 generate sampling data in GEE [random sampling]
- Gee series: unit 6 building various remote sensing indexes in Google Earth engine
- 摆正元素(带过渡动画)
- Paddlepaddle project source code
- Super detailed pycharm tutorial
- Global and Chinese market of cell culture freezers 2022-2028: Research Report on technology, participants, trends, market size and share
- Pycharm breakpoint management: temporarily cancel some breakpoints + run directly to a line
- Foreign trade marketing website system development function case making
- Implementation of leetcode two number addition go
猜你喜欢
![Gee series: unit 7 remote sensing image classification using GEE [random forest classification]](/img/01/ba9441b7b1efaed85c464316740edb.jpg)
Gee series: unit 7 remote sensing image classification using GEE [random forest classification]
![Gee series: unit 8 time series analysis in Google Earth engine [time series]](/img/a6/648ff959af93c22dc8605215a90535.jpg)
Gee series: unit 8 time series analysis in Google Earth engine [time series]

Fabric.js 居中元素

Gee dataset: chirps pentad high resolution global grid rainfall dataset
![Gee: explore the characteristics of precipitation change in the Yellow River Basin in the past 10 years [pixel by pixel analysis]](/img/ff/59956c2323567cc614458a2bccb642.jpg)
Gee: explore the characteristics of precipitation change in the Yellow River Basin in the past 10 years [pixel by pixel analysis]

Record my pytorch installation process and errors
![[opencv] image binarization](/img/7e/b56a59ffae3bf6cac9c0bb7e090b85.jpg)
[opencv] image binarization
![Gee series: Unit 5 remote sensing image preprocessing [GEE grid preprocessing]](/img/1e/cf0aa09c2fce2278386f12eae4a6cd.jpg)
Gee series: Unit 5 remote sensing image preprocessing [GEE grid preprocessing]

Fabric.js 右键菜单

Collectors. Groupingby sort
随机推荐
Creation and destruction of function stack frames
案例分享|智慧化的西部机场
Fabric.js 渐变
Global and Chinese market of impact roll 2022-2028: Research Report on technology, participants, trends, market size and share
Leetcode18题 【四数之和】递归解法
Gee: create a new feature and set corresponding attributes
Express logistics quick query method, set the unsigned doc No. to refresh and query automatically
Fabric.js IText 上标和下标
LS1046nfs挂载文件系统
LeetCode 1175. Prime number arrangement (prime number judgment + Combinatorial Mathematics)
ERP management system development and design existing source code
C# 图片显示占用问题
Map in JS (including leetcode examples)
el form 表单validate成功后没有执行逻辑
函数中使用sizeof(arr) / sizeof(arr[0])求数组长度不正确的原因
Simple and practical accounting software, so that accounts can be checked
画波形图_数字IC
JS interview collection test question 1
Global and Chinese market of commercial fish tanks 2022-2028: Research Report on technology, participants, trends, market size and share
fastText文本分类