Javascript 复制动态上载的图像

Javascript 复制动态上载的图像,javascript,jquery,html,html5-canvas,Javascript,Jquery,Html,Html5 Canvas,我正在尝试复制动态上传的图像。我用drawImage来做这个。如何使用drawImage复制动态上载的图像,同时保持纵横比 一个例子 html: 如果还有其他更好的方法,我愿意接受。您可以通过以下方法保持图像的高度和宽度: $("#button1").click(function(){ alert("sdfsfsdf") var ctx = $('#lcv_1').get(0).getContext('2d'); var img = $('#profile_pic').get(0);

我正在尝试复制动态上传的图像。我用drawImage来做这个。如何使用drawImage复制动态上载的图像,同时保持纵横比

一个例子

html:


如果还有其他更好的方法,我愿意接受。您可以通过以下方法保持图像的高度和宽度:

$("#button1").click(function(){
  alert("sdfsfsdf")
  var ctx = $('#lcv_1').get(0).getContext('2d');
  var img = $('#profile_pic').get(0);
  ctx.drawImage(img,0,0,img.width, img.height);
});

您可以做的是计算在可用区域内适合图像所需的比例。如果图像太高或太宽,这应该可以工作

它还将放大较小的图像以适应该区域,因此,如果您不想这样做,只需将比例限制为1即可

var areaWidth = 300,
    areaHeight = 150;
var scale = Math.min(areaWidth / img.width, areaHeight / img.height);
ctx.drawImage(img, 0, 0, img.width * scale, img.height * scale);
编辑:

尝试以下操作:

将图像宽度和高度乘以所需的百分比:

$("#button1").click(function(){
    var ctx = $('#lcv_1').get(0).getContext('2d');
    var img = $('#profile_pic').get(0);
    ctx.drawImage(img,0,0, img.width * 0.50, img.height * 0.50);
 });

我将图像居中放置在画布上,以保持纵横比。 更新


获取图像大小并使用它们将其粘贴到画布上。在你的代码中,你使用的是硬编码的大小。你想保持原始图像的大小,还是将其缩放到画布的大小?@MarcoCI:谢谢。画布具有固定大小。我希望在画布内绘制图像,以保持其纵横比。@imcg:谢谢。我想缩放图像以适应画布大小,同时保持其纵横比。只绘制了图像的一半?谢谢。这是行不通的,因为正如我提到的,原始图像是动态的。不能有固定的百分比。这似乎有效。但是如果页面上有多个canvas元素,那么当使用canvas这个词时会出现问题吗?e、 g:ctx.canvas.height?画布是否应该由某个变量名引用?多个画布元素没有问题。每个上下文都有一个属性画布。不,~canvas~应该保持原样。感谢您的帮助和提示!!
var areaWidth = 300,
    areaHeight = 150;
var scale = Math.min(areaWidth / img.width, areaHeight / img.height);
ctx.drawImage(img, 0, 0, img.width * scale, img.height * scale);
$("#button1").click(function(){
    var ctx = $('#lcv_1').get(0).getContext('2d');
    var img = $('#profile_pic').get(0);
    ctx.drawImage(img,0,0, img.width * 0.50, img.height * 0.50);
 });
 $("#button1").click(function(){
        //alert("sdfsfsdf")
        var ctx = $('#lcv_1').get(0).getContext('2d');
        var img = $('#profile_pic').get(0);
        var width = ctx.canvas.width;
        var height = ctx.canvas.width * (img.height / img.width);
        if (height > ctx.canvas.height) {
            height = ctx.canvas.height;
            width = ctx.canvas.height * (img.width / img.height);
        }
        ctx.drawImage(img,(ctx.canvas.width - width) / 2, (ctx.canvas.height - height) / 2, width, height);
  });