在通过onload在画布上绘制文本时,文本是粒状/模糊的 [英] text is grainy/blurry when drawing text on a canvas via onload

查看:109
本文介绍了在通过onload在画布上绘制文本时,文本是粒状/模糊的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我尝试在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);
}


解决方案

  ctx.fillText('hello ...',c.width / 2,c.height / 2);因为如果你例如用css设置画布的宽度,那么 c。 width  c.height 将是画布的默认大小,即300x150,而不是css中定义的大小。尝试为您的应用程序的全局宽度和高度设置两个变量。例如

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

,然后在您的代码中,您可以使用 canvasWidth 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


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

解决方案

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 = 400px;
var canvasHeight = 200px;
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

这篇关于在通过onload在画布上绘制文本时,文本是粒状/模糊的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆