2016-04-15 32 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(); 
} 

因此,它应该不会影响用户在相同的相对位置和大小下画布的大小。