Search code examples
javascripthtmlcanvas

HTML5 - Canvas, drawImage() draws image blurry


I am trying to draw the following image to a canvas but it appears blurry despite defining the size of the canvas. As you can see below, the image is crisp and clear whereas on the canvas, it is blurry and pixelated.

enter image description here

and here is how it looks (the left one being the original and the right one being the drawn-on canvas and blurry.)

enter image description here

What am I doing wrong?

console.log('Hello world')

var c = document.getElementById('canvas')
var ctx = c.getContext('2d')
var playerImg = new Image()

// http://i.imgur.com/ruZv0dl.png sees a CLEAR, CRISP image
playerImg.src = 'http://i.imgur.com/ruZv0dl.png'
playerImg.width = 32
playerImg.height = 32

playerImg.onload = function() {
  ctx.drawImage(playerImg, 0, 0, 32, 32);
};
#canvas {
  background: #ABABAB;
  position: relative;
  height: 352px;
  width: 512px;
  z-index: 1;
}
<canvas id="canvas" height="352" width="521"></canvas>


Solution

  • The reason this is happening is because of Anti Aliasing. Simply set the imageSmoothingEnabled to false like so

    context.imageSmoothingEnabled = false;
    

    Here is a jsFiddle verson

    jsFiddle : https://jsfiddle.net/mt8sk9cb/

    var c = document.getElementById('canvas')
    var ctx = c.getContext('2d')
    var playerImg = new Image()
    
    // http://i.imgur.com/ruZv0dl.png sees a CLEAR, CRISP image
    playerImg.src = 'http://i.imgur.com/ruZv0dl.png'
    
    playerImg.onload = function() {
      ctx.imageSmoothingEnabled = false;
      ctx.drawImage(playerImg, 0, 0, 256, 256);
    };