body {
  height: 100%;
  margin: 0;
  padding: 0;
  background: black;

canvas {
  box-sizing: border-box;
  position: relative;
  background: white;
  padding: 0;
  margin: auto;
  display: block;
// Alter "canvasDims" to play around with the canvas's dimensions
const canvas = document.querySelector("canvas"),
  canvasDims = { width: 300, height: 150 };
// keep content dimensions proportionate
canvas.width = canvasDims.width;
canvas.height = canvasDims.height;
// Edit the dimensions to see how the sizing adapts to different aspect ratios. This will be used in later calculations to determine the proper fit. If you're on a larger device, try resizing the screen to see how the canvas adapts and maintains aspect ratio.

function theatorFit() {
  calculate dimensions for if the width was the screen width, and the height was still proportionate. This will be used in a later calculation.
  formula for getting new height using new width and aspect ratio:
  aspectRatio = oldHeight/oldWidth;
  newHeight = aspectRatio*newWidth;
  let dims = {
    width: window.innerWidth,
    height: (canvasDims.height / canvasDims.width) * window.innerWidth

  /* set aspect ratio in CSS. This ensures that the element is always a certain aspect ratio, even if width or height isn't given. 
  aspect ratio is given by the formula: width/height = aspectRatio;
  canvas.style.aspectRatio = canvasDims.width / canvasDims.height;

  use "dims" to determine proper fit.

  If the screen height is more than the new canvas height when the width of the canvas is maximized, that means theres vertical space, and none of the height will be cut off, so we maximize the width, and set height to initial as to allow it to naturally conform to the aspect ratio (incase it was previously set to 100%).

Otherwise, if the new canvas height is more than the screen height, that means some of the canvas height will be cut off by the viewport, therefore we should maximize the height instead, and set the width to initial.
  if (window.innerHeight > dims.height) {
    canvas.style.width = "100%";
    canvas.style.height = "initial";
    canvas.style.top = `calc(50% - ${dims.height + "px"}/2)`;
  } else {
    canvas.style.height = "100%";
    canvas.style.width = "initial";
    canvas.style.top = "initial";

window.onresize = theatorFit;


External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.