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();
});

functionscale() {
  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));
  }

}

functionscalePreserveAspectRatio(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;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><h4>Container=blue, Canvas=red</h4>
Width:&nbsp
<inputtype=rangeid=containerWidthmin=100max=500value=350><br>Height:&nbsp
<inputtype=rangeid=containerHeightmin=100max=300value=200><divid=container><canvasid="canvas"width=300height=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?"