2015-10-20 24 views
0

我正在設計一個網頁,允許用戶上傳圖像並進行測量(計數,長度和角度)。同時使用jQuery和fabric.js - 用戶可以推動三個按鈕之一進行適當的分析(即計數,長度或角度)。但是,目前我無法弄清楚如何在保留用戶上傳的背景圖片的同時從一個畫布中移除對象。任何幫助不勝感激。如何從織物js畫布中移除物體,同時保留背景圖像

回答

0

你只需要調用clear畫布的方法。 看看下面的可執行代碼片段(or this 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/*" />