调整画布上的照片大小,而不会损失长宽比 [英] Resizing photo on a canvas without losing the aspect ratio

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

问题描述

您好,感谢您提前的任何帮助。我写一个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.

在处理canvas时不要使用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天全站免登陆