强制画布更新 [英] forcing canvas update
问题描述
有什么办法强制画布更新吗?我想显示一个加载消息,但游戏锁定加载之前,显示。我觉得我需要在调用加载函数之前告诉画布现在绘制,但也许还有另一种方法...
Is there any way to force a canvas to update? I'd like to display a loading message but the game locks up loading before it displays. I feel like I need to tell the canvas to "draw now" before load function is called, but maybe there is a another way...
编辑:
确定,只是为了清楚我写了一个非常小的肮脏的脚本(最好的我可以在我的茶歇:P)来演示我想要来的。这里:
ok, just to be clear i've written a very small dirty script (best i can do in my tea break :P) to demonstrate what i'm trying to over come. Here:
<html>
<head>
<title>test page</title>
</head>
<body onload="init();">
<canvas id="cnv" width="300" height="300">
canvas not supported.<br/>
</canvas>
</body>
</html>
<script type="text/javascript">
var ctx;
function init()
{
var canvas = document.getElementById('cnv');
ctx = canvas.getContext('2d');
ctx.fillStyle = "rgb(255, 0, 0)";
ctx.fillRect(0,0,300,300);
FakeLoad();
ctx.fillStyle = "rgb(0, 255, 0)";
ctx.fillRect(0,0,300,300);
}
function FakeLoad()
{
var d = new Date();
var start = d.getTime();
while (new Date().getTime() - start < 5000)
{
//emulate 5 secs of loading time
}
}
</script>
现在的想法是脚本应该绘制一个红色方块来显示其加载完成后。但所有你会看到,如果你复制到一个html文件是一个5秒的暂停,然后绿色出现,从不红色。在我的头,我想有一些命令像ctx.Refresh();后我画绿色广场告诉它更新现在!不要等!但从回复中判断这不是处理问题的方式。
now the idea is the script should draw a red square to show its "loading" and a green square when finished. but all you will see if you copy that into a html file is a pause of 5 seconds then the green appears, never red. In my head I wanted to have some command like ctx.Refresh(); after i draw the green square to tell it "update now! don't wait!" but judging from replies this is not the way to handle the problem.
我该怎么办? :)
推荐答案
另一件你可以做的,让你的画布在你做更长的任务之前显示FakeLoad超时:
Another thing you could do to allow the canvas to display before you do the longer task is begin FakeLoad after a short timeout:
var canvas = document.getElementById('cnv');
ctx = canvas.getContext('2d');
ctx.fillStyle = "rgb(255, 0, 0)";
ctx.fillRect(0,0,300,300);
setTimeout(function() {
FakeLoad();
ctx.fillStyle = "rgb(0, 255, 0)";
ctx.fillRect(0,0,300,300);
}, 20); // 20 ms - should be enough to draw something simple
这篇关于强制画布更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!