我正在使用 ionic 框架开发一个 Angular 移动应用程序。我有以下显示图像的功能。这适用于肖像图像的绘制和缩放,但风景图像似乎有点......被切断了。有任何想法吗?
$scope.drawBackground = function (imageUri) {
var context = canvas.getContext("2d");
var img = new Image();
img.src = imageUri;
img.onload = function () {
var orientation = "portrait";
if (img.naturalWidth > img.naturalHeight) {
orientation = "landscape";
}
canvas.width = orientation == "landscape" ? window.innerHeight : window.innerWidth;
canvas.height = orientation == "landscape" ? window.innerWidth : window.innerHeight;
var hRatio = canvas.width / img.width;
var vRatio = canvas.height / img.height;
var ratio = Math.min(hRatio, vRatio);
var center_X = (canvas.width - img.width * ratio) / 2;
var center_Y = (canvas.height - img.height * ratio) / 2;
context.clearRect(0, 0, canvas.width, canvas.height);
if (orientation == "landscape") {
context.translate(window.innerWidth, 0);
context.rotate(90 * Math.PI / 180);
}
context.drawImage(img, 0, 0, img.width, img.height, center_X, center_Y, img.width * ratio, img.height * ratio);
};
};
最佳答案
您正在使用 context.rotate(90 * Math.PI / 180);
旋转 Canvas 坐标系因此,当您绘制图像时,宽度在屏幕高度方向上,高度在负屏幕宽度方向上,中心 x 和 y 坐标也会切换。更改您的代码以将此考虑在内以解决您的问题。
顺便说一句 context.rotate(90 * Math.PI / 180);
90 进入 180 两次所以它变成 context.rotate(1 * Math.PI / 2);
乘以 1 什么都不做所以它变成 context.rotate(Math.PI / 2);
保存一个乘法。使用弧度总是更好 360 == Math.PI*2
, 180 == Math.PI
如图所示90 == Math.PI/2
关于javascript - HTML canvas drawImage 不能正常用于横向图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32683265/