Images look blurred when I used canvasPattern as pointBackgroundColor

115 Views Asked by At

Expected Behavior

Images should look good without blur in all screen resolutions. It looks good in the PC resolution.

Current Behavior

Images looks blurred on mobile resolutions.

Here is my code

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.js"></script>

<canvas id="myChart"></canvas>

JS

var img = new Image();
img.src = "https://techvalor.net/images/avatars/generator/175_1536055288.png";

img.onload = function() {
var canvas = document.getElementById("myChart");

var tempCanvas = document.createElement("canvas");
var tCtx = tempCanvas.getContext("2d");

var size = 40;

tempCanvas.width = size;
tempCanvas.height = size;

tCtx.drawImage(img, 0, 0, img.width, img.height, -size / 2, -size / 2, size, size);         
tCtx.drawImage(img, 0, 0, img.width, img.height, size / 2, -size / 2, size, size); 
tCtx.drawImage(img, 0, 0, img.width, img.height, -size / 2, size / 2, size, size);         
tCtx.drawImage(img, 0, 0, img.width, img.height, size / 2, size / 2, size, size);

var ctx = canvas.getContext("2d");
var fillStyle = ctx.createPattern(tempCanvas, "repeat");

var chart = new Chart(ctx, {
  type: "line",
  data: {
    labels: ["Item 1", "Item 2", "Item 3", "Item 4"],
    datasets: [
      {
        data: [5, 20, 35, 45],
        pointBackgroundColor: fillStyle,
        pointRadius: 20,
        pointBorderColor: "rgb(0,0,0)"
      }
    ]
  },
  options: {
    hover: { mode: null },
    tooltips: { enabled: false }
  }
 });
};

Codepen

https://codepen.io/rajkumar-osm/full/ZPbOOe

I think it has something to do with devicePixelRatio, but I have no idea on how to consider it while drawing image on the canvas.

0

There are 0 best solutions below