2014-02-13 71 views
0

當前我正試圖使用​​jQuery拖放功能在畫布上繪製圖像。我試過這個。在畫布上應用可調整大小的圖像

<canvas id="c" width="200" height="200"></canvas> 
<br> 
<div style="display:inline-block;width:128px;height:128px;" id="wrapper"> 
    <img id="ico" src="https://cdn1.iconfinder.com/data/icons/windows-8-metro-style/128/mustache.png" /> 
</div> 

和JS

$('#wrapper').draggable(); 
$('#ico').resizable({ 
    aspectRatio: true, 
    handles: 'ne, se, sw, nw' 
}); 
$('#c').droppable({ 
    drop: function (event, ui) { 
     $('#wrapper').dblclick(function() { 
      var img = $('#ico'); 
      var ctxt = $("#c")[0].getContext("2d"); 
      var offs = $("#c").offset(); 
      var uiPos = img.offset(); 
      var x = uiPos.left - offs.left; 
      var y = uiPos.top - offs.top; 
      ctxt.drawImage(img[0], x, y); 
      $('#wrapper').remove(); 
     }); 
     return false; 
    } 
}); 

我現在面臨的問題是,當圖像被調整它不是新加的。 這是JSFiddle http://jsfiddle.net/MZpJ6/2/中的代碼。上面的代碼是從網站的其他答案中修改的,但我不想發送其他人的問題,因此我正在創建一個新的代碼。

謝謝。

回答

0

演示:http://jsfiddle.net/m1erickson/uxNSN/

您可以調整上的drawImage

drawImage(theImage,x,y,width,height); 

下面是如何獲得新的寬/高在的drawImage

使用使用選購的尺寸參數繪製在畫布上的圖像

保存在.resizable的resize事件調整大小尺寸

// first save a reference to the wrapper div 

var $wrapper=$("#wrapper");  

// then save the new size in the .resizable's resize event 

$('#ico').resizable({ 

    aspectRatio: true, 
    handles: 'ne, se, sw, nw', 
    resize:function(event,ui){ 
     $wrapper.newWidth=ui.size.width; 
     $wrapper.newHeight=ui.size.height; 
    }, 
}); 

然後你就可以使用drawImage方法的調整參數在.droppable的下跌事件:

$('#c').droppable({ 
    drop: function (event, ui) { 
     $('#wrapper').dblclick(function() { 
      var img = $('#ico'); 
      var ctxt = $("#c")[0].getContext("2d"); 
      var offs = $("#c").offset(); 
      var uiPos = img.offset(); 
      var x = uiPos.left - offs.left; 
      var y = uiPos.top - offs.top; 
      ctxt.drawImage(img[0], x, y,$wrapper.newWidth,$wrapper.newHeight); 
      $('#wrapper').remove(); 
     }); 
     return false; 
    } 
});   
+0

謝謝!這正是我想要實現的。 – Luchezar