Skip to content

Instantly share code, notes, and snippets.

@greg-kennedy
Last active April 9, 2024 02:27
Show Gist options
  • Save greg-kennedy/000280e70433eab5e6f7 to your computer and use it in GitHub Desktop.
Save greg-kennedy/000280e70433eab5e6f7 to your computer and use it in GitHub Desktop.
Full-window, proper aspect HTML5 canvas example
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Full-screen Canvas</title>
</head>
<body style="background:black">
<canvas id="canvas" style="position:fixed;background:green;">
Sorry, your browser does not appear to support HTML5 Canvas element.
</canvas>
<script src="FullScreenCanvas.js"></script>
<noscript>
Sorry, your browser does not appear to support Javascript.
</noscript>
</body>
</html>
//////////////////////
// CONSTANTS
var VIEWPORT_X = 1280;
var VIEWPORT_Y = 720;
var TARGET_RATIO = VIEWPORT_X / VIEWPORT_Y;
////////////////////////
// GLOBAL VARIABLES
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
////////////////////////
// FUNCTIONS
function resizeCanvas() {
// This function resizes the canvas,
// but tries to maintain the targetRatio (above).
if ((window.innerWidth / window.innerHeight) > TARGET_RATIO) {
// window is too wide
canvas.height = window.innerHeight;
canvas.width = canvas.height * TARGET_RATIO;
canvas.style.top = "0px";
canvas.style.left = ((window.innerWidth - canvas.width) / 2) + "px";
} else {
canvas.width = window.innerWidth;
canvas.height = canvas.width / TARGET_RATIO;
canvas.style.top = ((window.innerHeight - canvas.height) / 2) + "px";
canvas.style.left = "0px";
}
// This next block zooms the canvas,
// so keep all your draw calls inside VIEWPORT_X or Y and it should Just Work.
// Note that changing canvas.width or canvas.height also
// * clears the canvas, and * resets the transformation matrix.
var zoom = canvas.height / VIEWPORT_Y;
context.scale(zoom,zoom);
}
////////////////////////
// INITIALIZATION
window.addEventListener("resize",resizeCanvas);
resizeCanvas();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment