繁体   English   中英

如何在保留背景图像的同时从面料js画布中删除对象

[英]how to remove objects from a fabric js canvas while preserving the background image

我正在设计一个允许用户上传图像并进行测量(计数,长度和角度)的网页。 同时使用jQuery和fabric.js-用户可以按三个按钮之一进行适当的分析(例如,计数,长度或角度)。 但是,目前我无法弄清楚如何在保留用户上传的背景图像的同时从一个画布中删除对象。 任何帮助,不胜感激。

您只需要调用canvas的clear方法即可。 看一下下面的可执行代码片段( 或此JSFiddle ),您可以将图像加载为背景,在其上绘制矩形并删除所有矩形。

 var eCommands; (function(eCommands) { eCommands[eCommands["None"] = 0] = "None"; eCommands[eCommands["Rect"] = 1] = "Rect"; eCommands[eCommands["Delete"] = 2] = "Delete"; })(eCommands || (eCommands = {})); var Application = (function() { function Application(canvas, rectButton, deleteButton, uploadButton) { this._currentCommand = eCommands.None; this._canvas = new fabric.Canvas(canvas); this._rectButton = rectButton; this._deleteButton = deleteButton; this._uploadButton = uploadButton; var cc = this._currentCommand; var c = this._canvas; var self = this; this._drawRect = function() { self._currentCommand = eCommands.Rect; }; this._delete = function() { c.clear(); }; this._executeCurrentCommand = function(e) { switch (self._currentCommand) { case eCommands.Rect: var rect = new fabric.Rect({ left: c.getPointer(ee).x - 10, top: c.getPointer(ee).y - 10, fill: 'red', width: 20, height: 20 }); c.add(rect); c.renderAll.bind(c); break; } }; this._drawBackground = function(e) { var reader = new FileReader(); reader.onload = function(event) { c.setBackgroundImage(event.target.result, c.renderAll.bind(c), {}); }; reader.readAsDataURL(e.target.files[0]); }; this._rectButton.addEventListener('click', this._drawRect, false); this._deleteButton.addEventListener('click', this._delete, false); this._uploadButton.addEventListener('change', this._drawBackground, false); this._canvas.on('mouse:up', this._executeCurrentCommand); } return Application; })(); var p = new Application(document.getElementById('c'), document.getElementById('btn_rect'), document.getElementById('btn_delete'), document.getElementById('btn_upload')); 
 #c { border: 1px solid #333; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script> <canvas id="c" width="500" height="150"></canvas> <br /> <input type="button" value="Rect Command" id="btn_rect" /> <input type="button" value="Delete Command" id="btn_delete" /> <input type="file" id="btn_upload" accept="image/*" /> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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