HTML5 Canvas drawings like lines are looking blurry


The task we are going to perform in this article is about HTML5 canvas drawings like lines are looking blurry.

We observe blurry effects because different device’s pixel ratios are varied. The browser or device using to view the canvas frequently affects how blurry the image is.

The gadget Pixel Ratio of Window interface returns the proportion of the display device's physical pixels to its CSS pixels for resolution. This number can also be understood as the proportion of physical to CSS pixels, or the size of one pixel to another pixel.

Let’s dive into the following examples to understand more about HTML5 canvas drawing like lines are looking blurry.

Example 1

In the following example we are taking the simple text which is blurry to make it clear.

We are considering this image which was blurry

<!DOCTYPE html>
<html>
<body>
   <canvas id="my tutorial"
      style="border:1px solid black;">
   </canvas>
   <script>
      var canvas = document.getElementById('my tutorial');
      var ctx = canvas.getContext('2d');
      window.devicePixelRatio=2;
      var size = 170;
      
      canvas.style.width = size + "px";
      canvas.style.height = size + "px";
      var scale = window.devicePixelRatio;
      
      canvas.width = Math.floor(size * scale);
      canvas.height = Math.floor(size * scale);
      
      ctx.scale(scale, scale);
      ctx.font = '10px Arial';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      
      var x = size / 2;
      var y = size / 2;
      var textString = "TUTORIALSPOINT";
      ctx.fillText(textString, x, y);
   </script>
</body>
</html>

When the script gets executed, it will generate the output of text, which we have considered as an example above without getting blurred.

Example 2

Considering the another where we the drawing look likes little blurry.

<!DOCTYPE html>
<html>
   <style>
      div {
          border: 1px solid black;
          width: 100px;
          height: 100px;
      }
      canvas, div {background-color: #F5F5F5;}
      canvas {border: 1px solid white;display: block;}
   </style>
<body>
    <table>
        <tr><td>Line on canvas:</td></tr>
        <tr><td><canvas id="tutorial" width="100" height="100"></td><td><div> </div></td></tr>
    </table>
    <script>
       var ctx = document.getElementById("tutorial").getContext("2d");
       ctx.lineWidth = 1;
       ctx.moveTo(2, 2);
       ctx.lineTo(98, 2);
       ctx.lineTo(98, 98);
       ctx.lineTo(2, 98);
       ctx.lineTo(2, 2);
       ctx.stroke();
    </script>
</body>
</html>

When the above script is run, the output window appears, displaying a blurry line on canvas with a 1pixel border on the webpage.

Updated on: 16-Dec-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements