Datsik
Datsik

Reputation: 14824

Image gets distorted when using css to set canvas height/width 100%

I am currently trying to draw an image to canvas, I have this so far:

"use strict";

var debugging = true;
var canvas = document.getElementById('astoniaCanvas');
var ctx = canvas.getContext('2d');

function loadUI() {
   var topOverlay = new Image();
   topOverlay.src = "/images/00000999.png";
   topOverlay.onload = function() {
       ctx.drawImage(topOverlay, 0, 0, canvas.width, 10);
   }

   var bottomOverlay = new Image();
   bottomOverlay.src = "/images/00000998.png";

   if (debugging) {
    console.log('Drawing');
   }
}


loadUI();

That works fine, but the image loads and looks like this:

enter image description here

When it should look like this:

enter image description here

The dimensions of the good looking picture are 800x40.

If I remove the

canvas {
    width: 100%;
    height: 100%;
}

the image goes back to looking normal, how can I scale my canvas?

Any information would be great thanks.

Upvotes: 1

Views: 309

Answers (1)

QBM5
QBM5

Reputation: 2788

You arent accounting for height. Canvas can be confusing when it comes to height/width vs clientHeight/clientWidth

When you create a canvas the css width and height has no bearing on the number of pixels the internal canvas contains. Unless specifically set a canvas comes with a width height of 300x150.

A trick I have used in the past is to use the clientWidth and a scale to set everything

"use strict";

var debugging = true;
var canvas = document.getElementById('astoniaCanvas');
var ctx = canvas.getContext('2d');

function loadUI() {
  var topOverlay = new Image();
  topOverlay.onload = function() {
   // use a scale between the image width and the canvas clientWidth  
    var scale = topOverlay.width / canvas.clientWidth;
    var newWidth = canvas.clientWidth;
    var newHeight = topOverlay.height * scale;
    // resize canvas based on clientWidth
    canvas.width = newWidth;
    canvas.height = newHeight;
    ctx.drawImage(topOverlay, 0, 0, newWidth, newHeight);
  }
  topOverlay.src = "https://i.sstatic.net/AJnjh.png";

  //  var bottomOverlay = new Image();
  //  bottomOverlay.src = "/images/00000998.png";

  if (debugging) {
    console.log('Drawing');
  }
}

loadUI()
<canvas id="astoniaCanvas" style="width: 100%"></canvas>

Upvotes: 1

Related Questions