Scale an image to fit when replacing an image - Javascript Canvas

Javascript examples for Canvas:image

Description

Scale an image to fit when replacing an image

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>Fabric kicking</title> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.0/fabric.js"></script> 
      <style>

#stage {/*from  w  w  w . j  a  v  a 2s . c  o m*/
   border: solid 1px #333;
}


      </style> 
   </head> 
   <body> 
      <button onclick="addImage('https://www.java2s.com/style/demo/Google-Chrome.png')">Add image</button> 
      <button onclick="addImage('https://www.java2s.com/style/demo/Google-Chrome.png')">add another image</button> 
      <canvas id="stage" width="600" height="600"></canvas> 
      <script>
    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 && oldHeight > img.getScaledHeight()){
            img.scaleToWidth(oldWidth);
            img.set({'height': oldHeight/img.scaleX})
          } else if (oldWidth > img.getScaledWidth()){
            img.scaleToHeight(oldHeight);
            img.set({'width': oldWidth/img.scaleY })
          }
          img.selectable = true
          canvas.add(img).setActiveObject(img);
        });
      }
      function addImage(url){
        setProductImage(url)
        canvas.renderAll()
      }
    
      </script> 
      <img src="https://www.java2s.com/style/demo/Google-Chrome.png"> 
      <img src="https://www.java2s.com/style/demo/Google-Chrome.png">  
   </body>
</html>

Related Tutorials