简体   繁体   中英

Fabric js - start free drawing if mouse in DIV

There was a task to do a function with the Fabric Js library (free drawing). Is it possible to make it so that when changing the Boolean variable canvas.isDrawingMode = false // true - if true , then draw always, regardless of whether the left mouse button is held down, if false - do not draw?

 var canvas = new fabric.Canvas('sheet'); canvas.isDrawingMode = true; canvas.freeDrawingBrush.width = 2; canvas.freeDrawingBrush.color = "#ff0000"; canvas.setHeight(window.innerHeight); canvas.setWidth(window.innerWidth); $(window).mouseup(function() { canvas.clear(); });
 <!DOCTYPE html> <html> <head> <style> #sheet { background-color: yellow; } </style> </head> <body> <canvas id="sheet"></canvas> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.6/fabric.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </body> </html>

One solution would be to call fabric's internal _onMouseDownInDrawingMode() / _onMouseUpInDrawingMode() on mouse:over / mouse:out events. However, since mouse:over event is not called when mouse enters over an existing fabric.js object (eg a part of a path), we'll need to tinker with the fabric.Canvas.prototype._onMouseEnter() a little bit.

Here's a complete solution:

 fabric.Canvas.prototype._onMouseEnter = (function (original) { return function (e) { if (this.isDrawingMode) { // reset cached pointer, otherwise new path will be started from the point cursor last left the canvas this._resetTransformEventData(); this._onMouseDownInDrawingMode(e); } } return original.apply(this, arguments) })(fabric.Canvas.prototype._onMouseEnter) var canvas = new fabric.Canvas('sheet'); canvas.on('mouse:out', function (e) { if (this.isDrawingMode) { this._onMouseUpInDrawingMode(e) } }); canvas.isDrawingMode = true; canvas.freeDrawingBrush.width = 2; canvas.freeDrawingBrush.color = "#ff0000"; canvas.setHeight(window.innerHeight); canvas.setWidth(window.innerWidth);
 <!DOCTYPE html> <html> <head> <style> #sheet { background-color: yellow; } </style> </head> <body> <canvas width="100" height="100" id="sheet"></canvas> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.6/fabric.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM