Skip to content Skip to sidebar Skip to footer

Making A Canvas Game Responsive On Resize

I am trying to make a pong canvas game responsive on resize, i am nor sure what i am missing and what would be the best way to have it responsive while still not being to process h

Solution 1:

Dont use the Resize event for animations.

(if you use requestAnimationFrame)

Do not add a resize to the resize event. The resize event does not fire in sync with the display, and it can also fire many time quicker than the display rate. This can make the resize and game feel sluggish while dragging at the window size controls.

Smooth and efficient resizing

For the smoothest resize simply check the canvas size inside the main loop. If the canvas does not match the containing element size then resize it. This ensures you only resize when needed and always resize in sync with the display (if you use requestAnimationFrame)

Eg

// get a reference to the element so you don't query the DOM each timeconst pongEl = document.getElementById("pong");

// then in the main loopfunctionmainLoop() {
    // do first thing inside the render loopif(canvas.width !== pongEl.offsetWidth  || canvas.height !== pongEl.offsetHeight ){
        canvas.width = pongEl.offsetWidth;
        canvas.height = pongEl.offsetHeight;   
        // note the above clears the canvas.
    }

    // game code as normalrequestAnimationFrame(mainLoop);
}

Solution 2:

You have to detect when the resize happens with JavaScript:

window.onresize = function(event) { ... };

and add a css class or properties to make the canvas width 100%. Also you have to give it a min-width to make sure no body can resize it to a really uncomfortable width.

Solution 3:

This piece of code needs to run again after a resize:

var canvas = document.createElement("canvas");
var width = document.getElementById('pong').offsetWidth;
var height = document.getElementById('pong').offsetHeight;
canvas.width = width;
canvas.height = height;
var context = canvas.getContext('2d');

Post a Comment for "Making A Canvas Game Responsive On Resize"