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.
and here is how it looks (the left one being the original and the right one being the drawn-on canvas and blurry.)
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>
Check the quality of any uploaded images If you've uploaded images into Canva and used them in your design, check if they're high resolution. Using low quality images can result in blurry or pixelated designs. Where possible, upload only high quality photos in 300 DPI.
To get around that, this is what we can do. const canvas = document. getElementById('canvas'); const context = canvas. getContext('2d'); const img = new Image(); img.
To do this you simply set the rendering context width and height to: target width and height * window. devicePixelRatio. canvas. width = target width * window.
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); };
Your problem is that your css constraints of canvas{width:512}
vs the canvas property width=521
will make your browser resample the whole canvas.
To avoid it, remove those css declarations.
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; z-index: 1; }
<canvas id="canvas" height="352" width="521"></canvas>
Also, if you were resampling the image (from 32x32 to some other size), @canvas' solution would have been the way to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With