复制动态上载的图像

Duplicate dynamically uploaded image

本文关键字:图像 上载 动态 复制      更新时间:2023-09-26

我正在尝试复制动态上传的图像。我正在使用drawImage()来执行此操作。如何使用drawImage()在保持纵横比的同时复制动态上传的图像?

小提琴示例

html:

<button id="button1">Picture</button>
<div id="main">
    <img id="profile_pic" src="http://upload.wikimedia.org/wikipedia/commons/thumb/a/aa/CocaColaBottle_background_free.png/200px-CocaColaBottle_background_free.png">
</div>
<div id="lgt_1">
    <div>
        <canvas id="lcv_1" class="drw"></canvas>
    </div>
</div>

js:

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

如果还有其他更好的方法,我愿意接受。

我已经将图像居中放置在画布上,保持纵横比
更新的小提琴。

 $("#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);
  });

你可以保持高度&图像宽度:

$("#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);
 });

http://jsfiddle.net/2uxj0v6u/3/