在画布上调整照片大小而不丢失纵横比 [英] Resizing photo on a canvas without losing the aspect ratio

查看:29
本文介绍了在画布上调整照片大小而不丢失纵横比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,感谢您提前提供的任何帮助.我正在编写一个 phonegap 应用程序,并且无法在不丢失外观或错误裁剪图像的情况下缩小照片.在下面的函数中,imageData"是相机拍摄的照片的 64 位字符串.我可以在我的页面上将图像绘制到画布上,但如果图片是横向拍摄的,那么它会被粉碎在一起.如果我不使用 scale 函数或 drawimage 函数对其进行缩放,那么我只会得到照片的顶角.一个例子:我拍了一张照片,onPhotoDataSuccess 函数中的图像宽度显示它是 1296px 宽和 968px 高.但我在 iPhone 上的画布是 272px 宽(纵向模式).我在网上尝试了许多不同的缩放方法,这似乎不是最接近的.我做错了什么?

Hi all thanks for any help in advance. I am writing a phonegap app and can not get the photo to shrink without either losing the aspect or cropping the image by mistake. In the function below "imageData" is a 64bit string of the photo that the camera took. I can draw the image onto the canvas on my page, but if the picture was taken in landscape then it is smashed together. If i do not scale it either by using the scale function or the drawimage function then i get only the top corner of the photo. A example: i took a photo the image width in the onPhotoDataSuccess function shows it to be 1296px wide, and 968px height. But my canvas on the iPhone is 272px wide (portrait mode). I have tried many different scaling methods on the web and this appears to be the closest by not quite. What am i doing wrong?

 function onPhotoDataSuccess(imageData) 
{
var myImage = new Image();
var thecanvas = document.getElementById("queImg");
var ctx = thecanvas.getContext("2d"); 
myImage.onload = function() 
  { 
    thecanvas.setAttribute('width', '100%');
    thecanvas.setAttribute('height', 'auto');
    ctx.scale((myImage.width * 0.15), (myImage.height * 0.15));  
    ctx.drawImage(myImage, 0, 0);   
    }     

    myImage.src = "data:image/jpeg;base64," + imageData;      
}

推荐答案

drawImage 内置了缩放功能.

Scaling is built in to drawImage.

在处理画布时不要使用 setAttribute,而是调用 canvas.width = 272,并且只能处理整个像素值.

Don't use setAttribute when dealing with canvas, call canvas.width = 272 instead, and only with whole pixel values.

这里有一些工作代码可以帮助您入门:

Here is some working code to get you started:

 function onPhotoDataSuccess(imageData)
{
var myImage = new Image();
var thecanvas = document.getElementById("queImg");
var ctx = thecanvas.getContext("2d");

    myImage.onload = function() {
    ctx.drawImage(myImage, 0, 0, myImage.width * 0.15, myImage.height * 0.15);
    }     

    myImage.src = "http://placekitten.com/1296/968";
}


onPhotoDataSuccess(null);

活生生的例子:

http://jsfiddle.net/QBTrg/6/

这篇关于在画布上调整照片大小而不丢失纵横比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆