Resizing photo on a canvas without losing the aspect ratio(在画布上调整照片大小而不丢失纵横比)
问题描述
大家好,感谢您提前提供的任何帮助.我正在编写一个 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/
这篇关于在画布上调整照片大小而不丢失纵横比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在画布上调整照片大小而不丢失纵横比
基础教程推荐
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01