2016-04-15 33 views
0

所以我使用的功能從本教程需要幫助重新定位了一圈,當畫布大小改變

http://www.html5rocks.com/en/tutorials/casestudies/gopherwoord-studios-resizing-html5-games/#disqus_thread

它看起來像這樣 -

function resizeGame() { 
     var gameArea = document.getElementById('canvas-container'); 
     var widthToHeight = 11/6; 
     var newWidth = window.innerWidth; 
     var newHeight = window.innerHeight; 
     var newWidthToHeight = newWidth/newHeight; 

     if (newWidthToHeight > widthToHeight) { 
      newWidth = newHeight * widthToHeight; 
      gameArea.style.height = newHeight + 'px'; 
      gameArea.style.width = newWidth + 'px'; 
     } else { 
      newHeight = newWidth/widthToHeight; 
      gameArea.style.width = newWidth + 'px'; 
      gameArea.style.height = newHeight + 'px'; 
     } 

     gameArea.style.marginTop = (-newHeight/2) + 'px'; 
     gameArea.style.marginLeft = (-newWidth/2) + 'px'; 

     var gameCanvas = document.getElementById('ctx'); 
     gameCanvas.width = newWidth; 
     gameCanvas.height = newHeight; 
     HEIGHT = newHeight; 
     WIDTH = newWidth 
    } 

所以一切,我使用寬度和高度在畫布上的位置很好。但是在我的遊戲中還有其他的東西,只是使用x和y,並且不會隨着畫布而改變。

if(drawBall){ 
       ctx.save(); 
       ctx.beginPath(); 
       ctx.arc(ball.x, ball.y, (ball.diameter/2) - 5,0, 2*Math.PI); 
       ctx.fillStyle = ball.color; 
       ctx.fill(); 
       ctx.restore(); 
      } 

我可以對我的ball.x和ball.y做些什麼來使它正確地隨着畫布變化?

+1

我們可以得到一個片段或小提琴,看看它運行時的樣子嗎? –

+0

我相信ball.x和ball.y是x和y的位置或座標。鑑於窗口的高度和寬度,這不會有特定的百分比,給你任何給定的座標? –

+0

所以我應該使用11/6的比例..? – joe

回答

0

這一切都歸結爲比例。知道在屏幕重新調整大小時可以隨時重新定位事物。

var ratio = { x:1, y: 1 }; 
function start(){ 
    ratio.x = canvas.width/canvas.clientWidth; 
    ratio.y = canvas.height/canvas.clientHeight; 
    drawSomething(); 
} 

function drawSomething(){ 
    context.rect(rectX * ratio.x, rectY * ratio.y, rectWidth * ratio.x, rectHeight * ratio.y); 
    /// stroke and all that good stuff 
} 

now listen for window change 
window.onresize = function(){ 
    // get new ratio's and draw again 
    start(); 
} 

因此,它應該不會影響用戶在相同的相對位置和大小下畫布的大小。