If you're interested in preserving aspect ratios and doing so in pure CSS (given the aspect ratio) you can do something like below. The key is the padding-bottom
on the ::content
element that sizes the container
element. This is sized relative to its parent's width, which is 100%
by default. The ratio specified here has to match up with the ratio of the sizes on the canvas
element.
// Javascript_x000D_
_x000D_
var canvas = document.querySelector('canvas'),_x000D_
context = canvas.getContext('2d');_x000D_
_x000D_
context.fillStyle = '#ff0000';_x000D_
context.fillRect(500, 200, 200, 200);_x000D_
_x000D_
context.fillStyle = '#000000';_x000D_
context.font = '30px serif';_x000D_
context.fillText('This is some text that should not be distorted, just scaled', 10, 40);
_x000D_
/*CSS*/_x000D_
_x000D_
.container {_x000D_
position: relative; _x000D_
background-color: green;_x000D_
}_x000D_
_x000D_
.container::after {_x000D_
content: ' ';_x000D_
display: block;_x000D_
padding: 0 0 50%;_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 0;_x000D_
left: 0;_x000D_
bottom: 0;_x000D_
}_x000D_
_x000D_
canvas {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}
_x000D_
<!-- HTML -->_x000D_
_x000D_
<div class=container>_x000D_
<div class=wrapper>_x000D_
<canvas width=1200 height=600></canvas> _x000D_
</div>_x000D_
</div>
_x000D_