Canvas Ratio Fix

by JQ Purfect

HTML

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css">
<div class="container">
  <div>
    <canvas id="canvas" width="600" height="400"></canvas>
  </div>
  <h4>
  Click the button to FIT new image...
  </h4>
  <input type="text" id="image-url" value="http://www.wallpapereast.com/static/images/abstract-iphone-6-wallpaper-full-images-101hd_JTr4ND5.jpg" />
  <button class="btn blue darken-2" id="fit-image">Ratio Fit</button>
</div>

CSS

body {
  padding: 15px;
}
.container {
  width: 100%;
 }
 
canvas {
   border: 1px solid red;
   width: 95vw;
   overflow: auto;
 }
 
 input {
   padding: 10px;
   width: 500px;
 }

JavaScript

$(document).ready(function() {

  var canvas = document.getElementById('canvas');
  var context = canvas.getContext('2d');
  var imageObj = new Image();
  imageObj.onload = function() {
    fitRatio(canvas, imageObj);
  };


  var fitRatio = function(canvas, imageObj) {
    context.clearRect(0, 0, canvas.width, canvas.height);

    var imageRatio = imageObj.width / imageObj.height;
    var canvasRatio = canvas.width / canvas.height;
    var renderableHeight, renderableWidth, xX, yY;
    if (imageRatio < canvasRatio) {
      renderableHeight = canvas.height;
      renderableWidth = imageObj.width * (renderableHeight / imageObj.height);
      xX = (canvas.width - renderableWidth) / 2;
      yY = 0;
    } else if (imageRatio > canvasRatio) {
      renderableWidth = canvas.width
      renderableHeight = imageObj.height * (renderableWidth / imageObj.width);
      xX = 0;
      yY = (canvas.height - renderableHeight) / 2;
    } else {
      renderableHeight = canvas.height;
      renderableWidth = canvas.width;
      xX = 0;
      yY = 0;
    }
    context.drawImage(imageObj, xX, yY, renderableWidth, renderableHeight);
  };


  imageObj.src = "http://www.samsung-wallpapers.com/uploads/allimg/140930/1-140930154A0.jpg";

  $("#fit-image").click(function() {
    imageObj.src = $("#image-url").val();
  });
});