Размытый текст в canvas

Почему у меня размывает текст Вот код

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

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
var balance = '3000';
let textBalance = "Balance:"+balance;
var background = new Image();
background.src = "./bg.png";
function textWidth(text){
    return Math.floor (ctx.measureText(text).width)
}
background.onload = function () {
    ctx.drawImage(background, 0,0, width, height); 
    ctx.beginPath();
    ctx.fillStyle = "rgba(42, 41, 41, 1)";
    ctx.fillRect(0, 0, width, height / 10);

    ctx.beginPath();
    ctx.fillStyle = "rgb(255, 0, 0)";
    ctx.fillRect(0, height / 10, width,2 );
    ctx.font = "6px Roboto ";
    ctx.fillStyle = "white";
    console.log(textWidth(textBalance))
    ctx.fillText(textBalance, width-textWidth(textBalance)-20, height/10-3);
}

введите сюда описание изображения


Ответы (1 шт):

Автор решения: Daniil Loban

Причина размытия зачастую бывает из-за несоответствия реальных размеров канваса и размеров задаваемых через стили. Еще бывает размытие линий при рисовании, это имеет другую причину, указав смещение в 0.5 пискелей можно добиться четкости.

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
var balance = '3000';
let textBalance = "Balance:"+balance;

function textWidth(text){
    return Math.floor (ctx.measureText(text).width)
}

ctx.beginPath();
ctx.fillStyle = "rgba(42, 41, 41, 1)";
ctx.fillRect(0, 0, width, height / 10);

ctx.fillStyle = "black"
ctx.rect(100, 100, 125, 125); // размытые линии
ctx.rect(250.5, 100.5, 125, 125); // четкие линии
ctx.stroke();

ctx.beginPath();
ctx.fillStyle = "rgb(255, 0, 0)";
ctx.fillRect(0, height / 10, width,2 );
ctx.font = "26px Roboto ";
ctx.fillStyle = "white";
ctx.fillText(textBalance, width-textWidth(textBalance)-20, height/10-3);
canvas {
  width: 500px;
  height:500px;
}
<canvas id="canvas" width="500" height="500"></canvas>

→ Ссылка