1

I try to translate a webgame from Flash to HTML5 with sprites in pixel art, and what I see is that the canvas is blurry compared to Flash where we can clearly discern the pixels.

<!DOCTYPE html>
<html>
<body>
  <canvas id="c" style="border: 1px solid black;"></canvas>
  <script>
  var ctx = document.getElementById("c").getContext("2d");
  ctx.imageSmoothingEnabled = false;
  var img = new Image();
  img.src = "https://i.imgur.com/kSEDvba.png";
  ctx.drawImage(img,10,10);
  </script>
</body>
</html>

Yes, it's slight, but I still want to fix it. I have already tried ctx.imageSmoothingEnabled = false; and the solution given by DiveintoHTML5 but it doesn't help.

Thank you for your help.

JacopoStanchi
  • 421
  • 5
  • 16
  • do you have larger copies of the sprites? try doubling the size – Pixelomo Mar 29 '18 at 03:11
  • 1
    The transalte 0.5 trick is **only** for 1px / 3px / 5px / ... wide strokes. Don't use it for drawImage. Now, to your problem, I can't see any blurring here. Are you on a high-res monitor? Or did you changed the zoom level of your browser? In this case, the blurring is caused by CSS and you can try to workaround it with poorly supported [`image-rendering` CSS rule](https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering), or by [setting your context's size](https://stackoverflow.com/questions/24395076/) so that CSS doesn't have to up-scale it. – Kaiido Mar 29 '18 at 03:28

1 Answers1

3

Apply the following css rule to your canvas element

Chrome: image-rendering: pixelated;

Firefox: image-rendering: optimizespeed;

diogenesgg
  • 2,601
  • 2
  • 20
  • 29
  • Thank you. Is there a way to cover all browsers? I can't set 2 times the `image-rendering` attribute can I? – JacopoStanchi Mar 29 '18 at 11:26
  • 1
    It's not fully supported. Take a look here https://caniuse.com/#search=image-rendering; Yes, you can set it 2 times, like the following: `canvas { image-rendering: pixelated; image-rendering: optimizespeed; }` – diogenesgg Mar 29 '18 at 13:11