问题描述
我正在研究HTML5移动应用程序。我正在使用画布元素和文件上传元素。
每当用户从手机上点击这个文件上传元素。他看到两种选择。
1.选择现有照片
2.拍摄新照片
I am working on HTML5 application for mobile. I am using a canvas element and file upload element.Whenever user hit this file upload element from mobile. He sees two options.1. Choose existing photo2. Take new photo
如果他选择现有照片,这在我的画布中很好固定,但如果他点击新照片,它不适合画布。宽度很好,但画布中显示的点击图片的高度不超过50px。
If he choose existing photo, this is fixed well in my canvas but if he clicks new photo, it does not fit into canvas. Width is fine but height of click image shown in canvas in not more than 50px.
我的HTML代码:
<canvas id="myCanvas" width="270" height="300"></canvas>
<input type="file" id="uploadImage" name="upload" value="Upload" onchange="PreviewImage();" />
我的Javascript代码
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
oFReader.onload = function (oFREvent) {
var canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, 270, 300);
imageUrl = oFREvent.target.result;
var base_image = new Image();
base_image.src = imageUrl;
base_image.onload = function () {
ctx.drawImage(base_image, 0, 0, 270, 300);
}
};
}
我搜索了很多网站,但找不到解决此问题的方法。
有什么帮助吗?
I have searched many sites but could not find solution of this issue.Any help?
推荐答案
我在 PreviewImage 函数中注意到的第一件事是:图像正被绘制到画布上:
The first thing I noticed in the PreviewImage function was where the image is being drawn to the canvas:
ctx.drawImage(base_image, 0, 0, 270, 300);
将调整图像的大小,忽略宽高比为270 x 300.如果删除它们,图像将呈现原始大小。
The last two attributes of CanvasRenderingContext2D.drawImage will resize the image, ignoring the aspect ratio, to 270 x 300. If you remove them the image will render at it's original size.
ctx.drawImage(base_image, 0, 0);
要将图片放在画布宽度内,请使用以下内容:
To fit the image within the width of the canvas use the following:
ctx.drawImage(base_image, 0, 0, canvas.width, base_image.height * (canvas.width / base_image.width));
至于具有奇怪高度(〜50px)的图像渲染,可能是与iOS相关的特定问题对2MB以上的图像进行二次采样。有关更多信息,请参阅。
As for the image rendering with a bizarre height (~50px) that could be an iOS specific issue related to images over 2MB getting subsampled. See HTML5 Canvas drawImage ratio bug iOS for more information.
这篇关于HTML5图像适合问题在画布中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!