title: Scale an image to fit when replacing an image
body: <p>I'm trying to implement a behaviour by which I can add an initial image to a canvas (placeholder) and then subsequently I can then choose a different image to replace that image - that new image should then scale itself to "fit" within the bounds of the old image. For example if I choose a portrait image as the "placeholder" and then choose a landscape image to replace it, Id expect the landscape image to first scale its width and maintain aspect ratio, and then vertically align itself within the boundaries of the placeholder dimensions.</p>
  
  <p>Here is a jsfiddle of what I have working so far: <a href="https://jsfiddle.net/cgallagher/co8dg527/1/" rel="nofollow noreferrer">https://jsfiddle.net/cgallagher/co8dg527/1/</a></p>
  
  <p>and here is the code:</p>
  
  <pre><code>var canvas = new fabric.Canvas('stage');
  var cw = canvas.getWidth()
  var ch = canvas.getHeight()
  var _currentImage;
  
  function setProductImage(url){
      var oldWidth; 
      var oldHeight;
      var oldLeft;
      var oldTop;
  
      fabric.Image.fromURL(url, function(img) {
        if (_currentImage) {
          oldWidth = _currentImage.getScaledWidth()
          oldHeight = _currentImage.getScaledHeight()
          oldLeft = _currentImage.left
          oldTop = _currentImage.top  
          canvas.remove(_currentImage);  
        }
  
        _currentImage = img;
  
        img.set({ 'left': oldLeft || 0 })
        img.set({ 'top': oldTop || 0 })
  
        if (oldHeight &amp;&amp; oldHeight &gt; img.getScaledHeight()){
          img.scaleToWidth(oldWidth);
          img.set({'height': oldHeight })
        } else if (oldWidth &gt; img.getScaledWidth()){
          img.scaleToHeight(oldHeight);
          img.set({'width': oldWidth })
        }
  
        img.selectable = true
        canvas.add(img).setActiveObject(img);
      });
    }
  
    function addImage(url){
      setProductImage(url)
      canvas.renderAll()
    }      
  </code></pre>
  
  <p>You can see that the image does scale the way I'd like but it doesn't then align itself.</p>
  
  <p>I'm toying with the idea of dropping a bounding box around the image too and possibly trying to align and scale within that but I'm not sure this is even possible with fabric?</p>