0

I have the following in html:

<img id="MarkingImage"></img>                
<canvas id="MarkingCanvas"></canvas>

And on css:

#MarkingCanvas { width: 100%; background-color: #7986CB; height: 96%; }
#MarkingImage { position: absolute; }

And on js:

function LoadImage()
{
   var markingImage = new Image();

   markingImage.addEventListener('load', function() 
   {
       m_imageWidth = this.naturalWidth;
       m_imageHeight = this.naturalHeight;

       m_markingCanvasContext.drawImage(markingImage, 0, 0, m_imageWidth,  m_imageHeight);
   });
   markingImage.src = 'PICT0001.JPG';
}

The thing is that this output stretches the image and it's quality gets really poor (see attached "Original" and "Result"). Original Image

Result Image

When I debug, I can see that the sizes if my canvas are:

width - 1410 height - 775

The sizes if my image are:

width - 551 height - 335

So my question is: why isn't the image placed in it's original size? I mean, there's enough space on the canvas. Also, why does the image gets stretched, and as a result gets in pretty low quality. Appears like it stretches beyond the size of the canvas.

What am I missing here?

Idanis
  • 1,918
  • 6
  • 38
  • 69
  • 2
    See [this answer](http://stackoverflow.com/questions/4938346/canvas-width-and-height-in-html5). You should define the canvas' height and width properties instead of using css. – R. Schifini Mar 29 '17 at 14:39
  • Ok, that helped thanks! But then the dimensions are hard-coded, and if I open the website on a, laptop, for example, then the canvas is too big, I wanted the size to be determined automatically. Is that possible? – Idanis Mar 29 '17 at 14:55
  • Also see [imageSmoothingEnabled](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/imageSmoothingEnabled) (and its equivalents, mozImageSmoothingEnabled & webkitImageSmoothingEnabled). This can sometimes affect image quality, but isn't supported on all browsers. – TheJim01 Mar 29 '17 at 16:16

1 Answers1

1

You need to set the canvas width and height dynamically according to the browser window's width and height. also, there is no need to use the image's naturalWidth / naturalHeight.

var m_markingCanvas = document.getElementById('MarkingCanvas');
var m_markingCanvasContext = m_markingCanvas.getContext('2d');

// setting canvas width and height dynamically
m_markingCanvas.width = window.innerWidth;
m_markingCanvas.height = window.innerHeight;

function LoadImage() {
    var markingImage = new Image();
    markingImage.addEventListener('load', function() {
        m_markingCanvasContext.drawImage(this, 0, 0);
    });
    markingImage.src = 'https://i.stack.imgur.com/a3Wpy.jpg';
}
LoadImage();
<canvas id="MarkingCanvas"></canvas>
ɢʀᴜɴᴛ
  • 32,025
  • 15
  • 116
  • 110