Search code examples
javascripthtml5-canvas

How come the canvas drawing is blurry, and how do I sharpen it?


The code is as follows:

const vs = document.getElementById("vs");
const vs_ctx = vs.getContext("2d");

vs_ctx.strokeStyle = "purple";
vs_ctx.lineWidth = 3;
vs_ctx.strokeRect(50, 50, 20, 20);
#vs {
    background-color: rgb(17, 17, 17);
}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>template</title>
        <link rel="stylesheet" href="css.css" />
    </head>
    <body>
        <canvas id="vs"></canvas>
        <script type="module" src="main.js"></script>
    </body>
</html>

I'm using no css to scale or set the canvas, as I read that will make stuff blurry. However, my simple square still is. How do I sharpen this?


Solution

  • Use image-rendering: pixelated; css property to turn off antialiasing

    document.querySelectorAll('canvas').forEach(canvas => {
      const ctx = canvas.getContext('2d')
      ctx.fillStyle = 'magenta'
      for (let i = 0; i < canvas.width; i += 1) {
        ctx.fillRect(i, i, 1, 1)
      }
    })
    canvas {
      width: 100px;
      height: 100px;
      border: 1px solid black;
    }
    
    .pixelated {
      image-rendering: pixelated;
    }
    <canvas width="10" height="10"></canvas>
    <canvas class="pixelated" width="10" height="10"></canvas>

    There is also this answer, but I'm pretty sure it doesn't work