2014-02-13 54 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