使用fabric.js在按钮上单击画布上添加图像

时间:2014-10-16 11:25:11

标签: javascript jquery html5 canvas fabricjs

我正在尝试在按钮上单击画布上添加图像。 。默认情况下,画布上有1个图像。点击按钮时会添加图像,但是当我点击画布时,所有图像都会被删除。只有背景图像保持不变。

 <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>

请帮我这个代码

1 个答案:

答案 0 :(得分:2)

在添加

之前尝试使用canvas.clear()