javascript - HTML canvas drawImage 不能正常用于横向图像

标签 javascript angularjs canvas html5-canvas ionic-framework

我正在使用 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/

相关文章:

javascript - NodeJS从缓冲区解码字符串返回多行字符串

javascript - 在 D3 图表的圆内插入文本

javascript - 是否可以将文本字段值绑定(bind)到数组特定索引中的元素?

css - ionic 中带有 ng-repeat 的列不会分成行

javascript - 无法将输入文本框附加到 Angular $scope

javascript - 如何将图像(以 HTML Canvas 中的数据 URL 形式给出)上传到 facebook?

javascript - 如何将 Google 表格中的列值与 Google Apps 脚本合并

javascript - 防止 ng-include 内容预加载,直到切换为显示

javascript - Canvas 全屏 100% 导致模糊

.net - 更改 Canvas 内控件的位置后,滚动条不可见