4

如果我尝试在 onload 事件中将文本绘制到画布上,文本会显示模糊。我稍后通过另一个功能的按钮单击绘制到同一个画布,这很好。但是如果我从按钮调用这个函数,它仍然是模糊的。有人能看出这段代码有什么问题吗?

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);
}
4

1 回答 1

3

可能有一些问题

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

因为如果您例如使用 css 设置画布的宽度,那么c.width并且c.height将是画布的默认大小,即 300x150,而不是在 css 中定义的大小。尝试为应用程序的全局宽度和高度设置两个变量。例如

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

然后稍后在您的代码中您可以使用canvasWidthand canvasWeight

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

看看这个测试: http: //jsfiddle.net/EsQfb/7/在你的情况下使用canvas.width而不是使用很重要canvas.style.width

看看这个以获取更多信息:http: //www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#attr-canvas-width

于 2013-02-10T10:00:34.520 回答