Text grainy / blurry when drawing text to canvas via onload

If I try to draw text on my canvas in the onload event, the text is blurry. I am drawing to the same canvas later by clicking a button with a different function, which is good. But if I call this function from the button, it still gets blurry. Can anyone see something wrong in this code?

window.onload = initCanvasRender;

function initCanvasRender() {
  var c = document.getElementById("canvas");
  var ctx = c.getContext('2d');
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillStyle = 'black';
  ctx.font = '20px Times New Roman';
  ctx.fillText('hello...', c.width/2, c.height/2);
}

      

+3


source to share


1 answer


There may be a problem with

ctx.fillText('hello...', c.width/2, c.height/2);

      

Because if you, for example, set the width of the canvas using css, then c.width

it c.height

will be the default size for the canvas, which is 300x150, and not the size defined in css. Try setting two variables for width and height that are global to your application. for example

var canvasWidth = 400px;
var canvasHeight = 200px;
c.width = canvasWidth;
c.height = canvasHeight;
/* ... */

      



and then in your code, you can use canvasWidth

and canvasWeight

:

ctx.fillText('hello...', canvasWidth/2, canvasHeight/2);

      

Take a look at this test: http://jsfiddle.net/EsQfb/7/ important to use canvas.width

, not canvas.style.width

in your case.

Take a look at this for more information: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#attr-canvas-width

+3


source







All Articles