Monday, 29 March 2021

Canvas causes fuzzy images when resized

When drawing images on canvas, they look fine with devicePixelRatio equal to 2. With the ratio set to 1, the image is blurry. If i set the display zoom to 200% (devicePixelRatio = 2) it becomes clear again. It also only happens when resizing the image. If you skip the fitToBox call and make the canvas larger so you can see it, the image looks fine. Here is a demo https://jsfiddle.net/7oc1e3ja/

enter image description here

const getImageFromUrl = (context, url, coords) => {
  return new Promise(resolve => {
    let img = new Image();
    img.src = url;

    img.onload = () => {
      fitToBox(img, coords);
      context.drawImage(img, coords.left, coords.top, img.width, img.height);
      resolve(img);
    }
  });
};

const fitToBox = (item, box) => {
    let ratio = Math.min(box.width / item.width, box.height / item.height);
    item.width *= ratio;
    item.height *= ratio;
};

const config = {
  imageUrl: 'https://i.imgur.com/y6viWyU.png',
  canvas: { width: 300, height: 300 },
};

let box = { ...config.canvas, top: 0, left: 0 },
    dpr = window.devicePixelRatio || 1,
    canvas = document.getElementById('c'),
    context = canvas.getContext('2d');

canvas.width = config.canvas.width * dpr;
canvas.height = config.canvas.height * dpr;
canvas.style.width = config.canvas.width + 'px';
canvas.style.height = config.canvas.height + 'px';
context.scale(dpr, dpr);

getImageFromUrl(context, config.imageUrl, box)
  .then(img => document.body.appendChild(img));


from Canvas causes fuzzy images when resized

No comments:

Post a Comment