简体   繁体   中英

add image on canvas on button click using fabric.js

I am trying to add images on button click on canvas. . By default there is 1 image on canvas. Images are getting added on button click, But all images are erased when i click on canvas. Only the background image remains constant.

 <html>
   <head>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <script src="http://code.jquery.com/jquery-1.10.1.js"></script>
   <script src="fabric.js"></script>
   </script>
   <script>
    function fun(){
      var canvas = window.canvas = new fabric.Canvas('c');

      fabric.Image.fromURL('compress/a.jpg', function(img){
      canvas.add(img.scale(0.1).set({ left: 150, top: 200, angle: 20 }));
   });

   $(canvas.wrapperEl).on('mousewheel', function(e) {
   var target = canvas.findTarget(e);
   var delta = e.originalEvent.wheelDelta / 120;

     if (target) {
     target.scaleX += delta;
     target.scaleY += delta;

      // constrain
       if (target.scaleX < 0.1) {
         target.scaleX = 0.1;
         target.scaleY = 0.1;
     }
       // constrain
       if (target.scaleX > 10) {
           target.scaleX = 10;
           target.scaleY = 10;
       }
         target.setCoords();
         canvas.renderAll();
         return false;
    }
  });
}



  function add()
 {
  window.canvas = new fabric.Canvas('c');


  window.canvas.getObjects();
  fabric.Image.fromURL('compress/b.jpg', function(img){
  window.canvas.add(img.scale(0.1).set({ left: 150, top: 200, angle: 20 }));
  window.canvas.selection = true;
   window.canvas.renderAll();
   window.canvas.calcOffset();
   });

  }
</script>
<style>
   canvas {
    border: 1px solid #999;
   }
  </style>
 </head>
  <body onload=fun()>
    <div id="test" align="center" style="display: block">
    <canvas id="c" width="600" height="600"></canvas>
    </div> 
     <button id="but" onclick="add()">add images</button>
    </body>
  </html>

Please help me with this code

尝试在添加之前使用canvas.clear()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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