[英]Fabric js - start free drawing if mouse in DIV
有一項任務是使用 Fabric Js 庫(免費繪圖)執行功能。 是否有可能在更改布爾變量canvas.isDrawingMode = false // true
- 如果為true
,則始終繪制,無論是否按住鼠標左鍵,如果為false
- 不繪制?
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>
一種解決方案是在mouse:over
/ mouse:out
事件上調用結構的內部_onMouseDownInDrawingMode()
/ _onMouseUpInDrawingMode()
。 然而,由於當鼠標進入現有的fabric.js 對象(例如路徑的一部分)時, mouse:over
事件不會被調用,我們需要稍微修改fabric.Canvas.prototype._onMouseEnter()
。
這是一個完整的解決方案:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.