HTML5/Canvas 中 context.fillText() 的奇怪行为
我对 context.fillText() 函数有一点问题。
当我使用它调用函数时,它不会绘制文本,除非我在启动“主循环”后调用它。在同一函数中调用的所有 context.fillRect() 都可以完美运行。
这是我的代码。我写了一些评论来强调它有效或无效的地方。
var pause = true;
function draw () {
if ( !pause ) {
redraw_everything();
}
else {
draw_popup(); // WORKAROUND
}
}
function draw_popup ( text ) {
ctx.fillStyle = 'red';
ctx.fillRect ( _x, _y, _w, _h );
ctx.fillStyle = 'black';
ctx.fillRect ( _in_x, _in_y, _in_w, _in_h );
ctx.font = theight + "pt Orbitron";
twidth = ctx.measureText ( text ).width;
ctx.fillStyle = 'red';
ctx.fillText ( text, _tx, _ty ); /** Draw the text */
ctx.restore();
}
function init() {
canvas = document.getElementById ( 'tutorial' );
ctx = canvas.getContext ( '2d' );
pause = false;
draw();
pause = true;
setInterval ( 'draw()', 20 );
draw_popup ( 'PacMan' ); // DOESN'T WORK
tutorial = document.getElementsByTagName( 'body' )[ 0 ];
tutorial.onkeypress = function ( e ) {
var c = String.fromCharCode( e.charCode ).toLowerCase();
if ( c == 'p' ) {
draw_popup ( 'Pause' ); // IT WORKS
}
}
}
您可以找到完整的源代码 此处
更新:根据要求,我做了一个更短的示例(未测试)。
I have a little problem with the context.fillText() function.
When I call a function using it, it doesn't draw the text, unless I call it after I start the "mainloop". All the context.fillRect()s called in the same function work perfectly.
Here is my code. I write a couple of comment to highlight where it works or doesn't work.
var pause = true;
function draw () {
if ( !pause ) {
redraw_everything();
}
else {
draw_popup(); // WORKAROUND
}
}
function draw_popup ( text ) {
ctx.fillStyle = 'red';
ctx.fillRect ( _x, _y, _w, _h );
ctx.fillStyle = 'black';
ctx.fillRect ( _in_x, _in_y, _in_w, _in_h );
ctx.font = theight + "pt Orbitron";
twidth = ctx.measureText ( text ).width;
ctx.fillStyle = 'red';
ctx.fillText ( text, _tx, _ty ); /** Draw the text */
ctx.restore();
}
function init() {
canvas = document.getElementById ( 'tutorial' );
ctx = canvas.getContext ( '2d' );
pause = false;
draw();
pause = true;
setInterval ( 'draw()', 20 );
draw_popup ( 'PacMan' ); // DOESN'T WORK
tutorial = document.getElementsByTagName( 'body' )[ 0 ];
tutorial.onkeypress = function ( e ) {
var c = String.fromCharCode( e.charCode ).toLowerCase();
if ( c == 'p' ) {
draw_popup ( 'Pause' ); // IT WORKS
}
}
}
You can find the full source code here
UPDATE: As requested, I made a shorter example (not tested).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我发现了问题。我正在使用 Google Webfont 集合中的字体。我第一次使用它时,字体还没有加载,所以它不会写。以下请求已加载字体,因此我工作
I found the problem. I am using a font from the Google Webfont collection. The first time i use it, the font isn't loaded yet, so it doesn't write. The following requests have the font already loaded, therefore i work