javascript - 通过 onload 在 Canvas 上绘制文本时,文本呈颗粒状/模糊

标签 javascript html canvas

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

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

最佳答案

可能有问题

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

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

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

稍后在您的代码中您可以使用 canvasWidthcanvasWeight:

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

关于javascript - 通过 onload 在 Canvas 上绘制文本时,文本呈颗粒状/模糊,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14796370/

相关文章:

javascript - 从 svg 或通过 canvas 的 svg 输出具有正确文件名的 300 个 png 图像?

javascript - FabricJS - 为什么形状内的旋转对象不垂直居中?

javascript - Chrome 浏览器版本 72.0.3626.96 错误触发<输入类型 ="file"> 从 javascript 函数单击(文件选择对话框)

javascript - 标准 "Match URL"的预期匹配请求 - 未找到 - Angular2+

jquery - 如何在免费的jqgrid中使用主体水平滚动条

html - Google Web 字体导入在堆栈末尾不起作用

javascript - Wildfly 允许 OPTIONS 方法但返回 405 不允许方法

javascript - Windows 8 应用程序是否在符合标准的 JavaScript、HTML5 和 CSS3 上运行?

jquery - 如何对 iframe 子元素应用 3D 变换?

HTML5 Canvas 和音频跨浏览器兼容性