text is grainy/blurry when drawing text on a canvas via onload

我的梦境 提交于 2020-01-14 12:35:07

问题


If I try to draw text to my canvas at the onload event, the text shows up blurry. I draw to the same canvas later via a button click from another function and it's fine. But if I call this function from the button, it's still blurry. Can anybody 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);
}

回答1:


There may be some problem with the

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

Because if you for example set width of the canvas with css then c.width and c.height will be the default size for the canvas which is, 300x150 and not the size defined in css. Try to set two variables for the width and height that are global for your application. E.g

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

and then later 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/ it's important to use use the canvas.width and not canvas.style.width in your case.

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



来源:https://stackoverflow.com/questions/14796370/text-is-grainy-blurry-when-drawing-text-on-a-canvas-via-onload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!