【问题标题】:HTML canvas drawImage not working correctly for landscape imagesHTML Canvas Trawimage无法正常工作景观图像
【发布时间】:2015-12-17 10:44:19
【问题描述】:

我正在使用 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);
        };
    };

【问题讨论】:

    标签: javascript angularjs canvas html5-canvas ionic-framework


    【解决方案1】:

    您正在使用context.rotate(90 * Math.PI / 180);旋转画布坐标系,因此当您绘制图像时,宽度为屏幕高度方向,高度为负屏幕宽度方向,中心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*2180 == Math.PI 和如图所示90 == Math.PI/2

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 2015-07-30
      • 2016-11-21
      • 2021-04-09
      • 1970-01-01
      • 1970-01-01
      • 2020-11-04
      相关资源
      最近更新 更多