Scale canvas width and height to be as large as possible but maintain aspect ratio (JS)
<p>If I have a canvas element that is a certain width and height, e.g.</p>

<pre><code>&lt;canvas id="display" width="900" height="650" tabindex=0&gt;&lt;/canvas&gt;
</code></pre>

<p>and I want to scale up the width and height of the canvas to as large as possible while being contained within the viewport <strong>without</strong> changing the aspect ratio or increasing the overall area for objects to be displayed within the canvas.</p>

<p>This means that if a window is width <code>2200</code> and height <code>1300</code>, both the display width and height of the canvas will be doubled (and no larger because otherwise the height could not be contained) and the canvas will have the new dimensions <code>1800</code> and <code>1300</code>.</p>

<p>However, I am scaling up the CSS display height of the canvas element, not the canvas itself, which means that <strong>objects inside the canvas should also have their dimensions increased.</strong></p>

<pre><code>canvas {
  width: ...
  height: ...
}
</code></pre>

<p>It would be even better if the canvas can rescale itself when the window is resized, perhaps with an event listener.</p>

<p>Is there any way to do this in JS?</p>