繁体   English   中英

HTML 画布 drawImage 对风景图像无法正常工作

[英]HTML canvas drawImage not working correctly for landscape images

我正在使用离子框架以角度开发移动应用程序。 我有以下显示图像的功能。 这适用于肖像图像的绘制和缩放,但风景图像似乎有点......切断。 有任何想法吗?

$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);旋转画布坐标系context.rotate(90 * Math.PI / 180); 因此,当您绘制图像时,宽度在屏幕高度方向,高度在负屏幕宽度方向,并且中心 x 和 y 坐标也会切换。 更改您的代码以考虑到这一点来解决您的问题。

BTW 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM