简体   繁体   English

HTML5画布使用for循环清除和重绘

[英]HTML5 canvas clearing and redrawing with for loop

I'm playing around with JS and found a small HTML5 game tutorial that I thought would be cool to modify. 我在玩JS,发现了一个小的HTML5游戏教程,我认为修改它很酷。 (This is the outcome: http://www.lostdecadegames.com/demos...e_canvas_game/ ) (这是结果: http : //www.lostdecadegames.com/demos...e_canvas_game/

So I modified it just a little bit, letting for loop draw the background. 因此,我做了一点修改,让for循环绘制背景。 The drawing itself succeed, but something is wrong with it. 绘图本身成功了,但是出了点问题。 I found out that I must clear the canvas and redraw everything to each frame. 我发现必须清除画布并将所有内容重新绘制到每一帧。 I did it like this: 我这样做是这样的:

ctx.clearRect(0,0,canvas.width,canvas.height);

The outcome was that the clearing happened before the loop finished drawing the images. 结果是清除发生在循环完成绘制图像之前。

The cycle is: 周期为:

  • clear canvas 透明帆布
  • for loop drawing the background tiles 用于循环绘制背景图块
  • draw something else 画些别的东西

Somehow it doesn't output the background tiles... 不知何故它不输出背景图块...

I included my modifications here: http://jsfiddle.net/swenn/6mWkU/ 我在这里包括了修改: http : //jsfiddle.net/swenn/6mWkU/

What might be the problem? 可能是什么问题?

I found the problem with your code, you aren't setting your tileY variable back to zero after drawing the floor. 我发现您的代码存在问题,绘制地板后没有将tileY变量设置回零。 This causes the canvas to draw it further and further down, eg not in the viewspace of the canvas. 这导致画布将其绘制得越来越远,例如不在画布的视区中。

//Start of your render function.
tileY = 0;
tileX = 0;

Working version, webkit 工作版本,Webkit

As I wrote in my comment, you should requestAnimationFrame to schedule your drawing. 正如我在评论中所写的那样,您应该requestAnimationFrame来安排您的绘图。

You might also want to look into a better way of drawing the floor, maybe making one larger texture and drawing it one time only instead of in a for loop. 您可能还想研究一种绘制地板的更好方法,也许制作一个更大的纹理并仅绘制一次而不是在for循环中绘制。

EDIT: Fixed the jsfiddle link to actually be the updated version. 编辑:修复了jsfiddle链接实际上是更新的版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM