SignaturePad aspect ratio bug workaround

by HugeHugh

HTML

<script src="https://szimek.github.io/signature_pad/js/signature_pad.umd.js"></script>
<div>
img tag with correct aspect ratio, for reference
</div>
<img width="400" src="https://ourlostfounding.com/wp-content/uploads/2017/01/John-Hancock-signature-1024x287.png">
<hr>
<div>
SignaturePad
</div>
<canvas id="signature-pad"></canvas>
<div>
The image has the correct aspect ratio, because additional parameters were provided about it's dimensions
</div>

CSS

body {
  font-family: sans-serif;
  background-color: #eee;
}
canvas, img {
  background-color: white;
}
canvas {
  width: 400px;
  height: 200px;
}

JavaScript

var startSig = 'https://ourlostfounding.com/wp-content/uploads/2017/01/John-Hancock-signature-1024x287.png'
var canvas = document.getElementById('signature-pad');

// Adjust canvas coordinate space taking into account pixel ratio,
// to make it look crisp on mobile devices.
// This also causes canvas to be cleared.
function resizeCanvas() {
    // When zoomed out to less than 100%, for some very strange reason,
    // some browsers report devicePixelRatio as less than 1
    // and only part of the canvas is cleared then.
    var ratio =  Math.max(window.devicePixelRatio || 1, 1);
    canvas.width = canvas.offsetWidth * ratio;
    canvas.height = canvas.offsetHeight * ratio;
    canvas.getContext("2d").scale(ratio, ratio);
}

// window.onresize = resizeCanvas;
// it does not matter if the resize routine with devicePixelRatio runs, or not.
// we can comment this out and the same problem arises, just with a smaller display
resizeCanvas();

var signaturePad = new SignaturePad(canvas);

var imgW, imgH;

var canvasW = 400, canvasH = 200;

getImageSize(startSig).then(() => {
// taken from https://stackoverflow.com/a/23105310/213050
	var hRatio = canvasW  / imgW;
   var vRatio =  canvasH / imgH;
   var ratio  = Math.min ( hRatio, vRatio );
   
   var width = imgW * ratio;
   var height = imgH * ratio;
   
	signaturePad.fromDataURL(startSig, { width, height, ratio });
});


function getImageSize(url) {
  return new Promise((resolve, _reject) => {
    var downloadedImg = new Image();
    downloadedImg.addEventListener(
      'load',
      () => {
        imgW = downloadedImg.width;
        imgH = downloadedImg.height;
        resolve();
      },
      false
    );
    downloadedImg.src = url;
  });
}