当画布尺寸发生变化时,需要帮助重新定位圆圈

时间:2016-04-15 03:48:01

标签: javascript css html5 canvas

所以我使用本教程中的函数

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
    }

因此,我使用WIDTH和HEIGHT在画布上定位的所有内容都可以正常工作。但是我在游戏中还有其他东西只使用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 :(得分: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();
}

有了这个,用户重新调整尺寸并不重要,画布将以相同的相对位置和大小绘制。