如何从fabric js画布中删除对象,同时保留背景图像

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

本文关键字:保留 图像 背景 对象 删除 fabric js 布中      更新时间:2023-09-26

我正在设计一个网页,允许用户上传图像并进行测量(计数,长度和角度)。同时使用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(e.e).x - 10,
            top: c.getPointer(e.e).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/*" />