2015-09-20 71 views
2

我正在開發使用離子框架的角度移動應用程序。我有以下功能來顯示圖像。這適用於繪製和縮放肖像圖像,但風景圖像似乎有點...切斷。有任何想法嗎?HTML畫布drawImage對於橫向圖像無法正常工作

$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); 
     }; 
    }; 

回答

2

您正在旋轉的畫布座標系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