Vpp Man
Vpp Man

Reputation: 2546

Drawing image in HTML5 canvas is blurry/squeezed

I am trying to draw an image on the canvas. Problem is, I was trying to draw it as contained within the canvas so that it would look good in different screen resolutions. But the image seems to be squeezed/blurred.

function drawImageScaled(img, ctx) {
  var canvas = ctx.canvas;
  var hRatio = canvas.width / img.width;
  var vRatio = canvas.height / img.height;
  var ratio = Math.min(hRatio, vRatio);
  var centerShift_x = (canvas.width - img.width * ratio) / 2;
  var centerShift_y = (canvas.height - img.height * ratio) / 2;
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.drawImage(img, 0, 0, img.width, img.height,
    centerShift_x, centerShift_y, img.width * ratio, img.height * ratio);
}

function draw() {
  var ctx = document.getElementById('floor_canvas');
  if (ctx.getContext) {
    ctx = ctx.getContext('2d');
    var bg_img = new Image();

    bg_img.onload = function() {
      drawImageScaled(bg_img, ctx);
    };

    bg_img.src = 'https://i.sstatic.net/FTm9g.jpg'; //'floor_plan/floor_1.jpg';
  }
}

draw();
#floor_canvas {
  width: 100%;
  height: 100vh;
}
<canvas id="floor_canvas"></canvas>

This is the original image. Viewing it directly shows it in high quality: https://i.sstatic.net/FTm9g.jpg

Any inputs regarding why it appears so?

Upvotes: 3

Views: 172

Answers (0)

Related Questions