Drawing the image on canvas makes it very blurry. But as the image is scaled up it gets crisp. I cannot figure out the problem.
image I am using : https://images.unsplash.com/photo-1512819432727-dbcb57a06f13?ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80
codepen link : https://codepen.io/AdnanHashmi/pen/eYNQPoX
Even zooming in on the page shows that the image drawn on canvas is blurred and smugged.
This is how it looks.
The left image here is the image drawn on canvas while the right one is put on the screen using tag.
My code:
const canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");
var dpi = window.devicePixelRatio;
var img = new Image();
img.src =
"https://images.unsplash.com/photo-1512819432727-dbcb57a06f13?ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80";
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
canvas.style.width = canvas.width.toString() + "px";
canvas.style.height = canvas.height.toString() + "px";
img.onload = () => {
var newWidth = canvas.width * dpi;
var newHeight = canvas.height * dpi;
canvas.style.width = newWidth.toString() + "px";
canvas.style.height = newHeight.toString() + "px";
ctx.drawImage(img, 100, 100, 100, 150);
};
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
canvas {
image-rendering: pixelated;
}
img[src$=".gif"],
img[src$=".png"] {
image-rendering: -moz-crisp-edges; /* Firefox */
image-rendering: -o-crisp-edges; /* Opera */
image-rendering: -webkit-optimize-contrast; /* Webkit (non-standard naming) */
image-rendering: crisp-edges;
-ms-interpolation-mode: nearest-neighbor; /* IE (non-standard property) */
}
.sharp {
position: absolute;
top: 100px;
left: 250px;
width: 100px;
height: 150px;
}
<canvas></canvas>
<img src="https://images.unsplash.com/photo-1512819432727-dbcb57a06f13?ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80" class="sharp" alt="" srcset="">