[英]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.