Skip to content Skip to sidebar Skip to footer

What CSS Can I Use That Will Scale The Canvas To Fill Its Container Without Changing Its Aspect Ratio?

I have a canvas with a specific size (lets, say 300x150). What CSS can I use that will scale the canvas to fill its container without changing its aspect ratio and center it both h

Solution 1:

This might be off topic given your question's tags, but here's a way with javascript.

Note: You can convert this example's jquery to pure javascript if desired--there's no critical use for the jquery.

var canvas = document.getElementById("canvas");
var cw = canvas.width;
var ch = canvas.height;
var $canvas = $('#canvas');
var $container = $('#container');
var $containerWidth = $('#containerWidth');
var $containerHeight = $('#containerHeight');
$containerWidth.val($container.css('width'));
$containerHeight.val($container.css('height'));
scale();

$('#containerWidth,#containerHeight').change(function() {
  scale();
});

function scale() {
  var containerW = $containerWidth.val();
  var containerH = $containerHeight.val();
  var scale = scalePreserveAspectRatio(cw, ch, containerW, containerH)
  $container.css('width', containerW);
  $container.css('height', containerH);
  $canvas.css('width', cw * scale);
  $canvas.css('height', ch * scale);
  if (Math.abs(containerW - cw * scale) < 2) {
    $canvas.css('top', parseInt((containerH - ch * scale) / 2));
    $canvas.css('left', 0);
  } else {
    $canvas.css('top', 0);
    $canvas.css('left', parseInt((containerW - cw * scale) / 2));
  }

}

function scalePreserveAspectRatio(canvasW, canvasH, maxW, maxH) {
  return (Math.min((maxW / canvasW), (maxH / canvasH)));
}
body {
  background-color: ivory;
}
#container {
  border: 1px solid blue;
  width: 350px;
  height: 200px;
  position: relative;
}
#canvas {
  border: 1px solid red;
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Container=blue, Canvas=red</h4>
Width:&nbsp
<input type=range id=containerWidth min=100 max=500 value=350>
<br>Height:&nbsp
<input type=range id=containerHeight min=100 max=300 value=200>
<div id=container>
  <canvas id="canvas" width=300 height=150></canvas>
</div>

Post a Comment for "What CSS Can I Use That Will Scale The Canvas To Fill Its Container Without Changing Its Aspect Ratio?"