HTML Canvas 分层框架
我正在使用 HTML 5 canvas 标签构建一个应用程序,到目前为止效果很好。该应用程序的下一步是分层,这样我就有了一个背景图像,并在其之上添加了一些图层。现在我正在这样做:
this.drawMarkers = function(markers) {
selectedImage = null;
map.width = map.width;
for(var i in markers) {
for(var j in markers[i]) {
var holder = markers[i][j];
if(holder !== null) {
var marker = new Marker(new Cell(holder.row, holder.column), holder.type);
marker.src = holder.src;
marker.draw();
}
}
}
initGrid();
}
其中i
是层,j
是该层上的东西。最初的代码只是将所有内容绘制在一层上,并且效果很好,如果所有内容都按正确的顺序下载,这一层也可以。如果没有,事情就会错误地堆叠。例如,如果背景很大并且最后下载,则由于所有内容都是异步的,因此最终会清除其上的所有内容。
是否有任何框架可以向画布添加分层以避免这种情况?如果事情没有按正确的顺序加载,只要保留堆叠,我就可以了。
I'm building an app using the HTML 5 canvas tag, and so far it works great. The next step for the app is layering, so that I have a background image and them some more layers on top of that. Right now I'm doing this:
this.drawMarkers = function(markers) {
selectedImage = null;
map.width = map.width;
for(var i in markers) {
for(var j in markers[i]) {
var holder = markers[i][j];
if(holder !== null) {
var marker = new Marker(new Cell(holder.row, holder.column), holder.type);
marker.src = holder.src;
marker.draw();
}
}
}
initGrid();
}
where i
is the layer and j
is the things on that layer. The initial code for this just drew everything on one layer and it worked great, and this one does too if everything downloads in the correct order. If not, things get stacked incorrectly. For example, if the background is large and ends up downloading last, it ends up clearing out everything on top of it due to everything being asynchronous.
Are there any frameworks out there for adding layering to canvas to avoid this? I'm fine if things don't load in the correct order, so long as the stacking is preserved.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先要问自己一个问题:
如果你重复绘制它,比如每 100 毫秒绘制一次,问题会消失吗?
如果不是,则“以错误的顺序绘制”是您正在做的事情,而不是异步错误。我怀疑情况可能是这样。
图像可能无法绘制,但假设您的
绘制
例程是正确的并且您每次都重新绘制所有内容,则任何内容都不应以错误的顺序绘制。根据画布规范,如果未加载图像,对drawImage的调用不会执行任何操作,因此除非是您自己的调用顺序,否则错误的堆叠应该是不可能的。无论如何,您应该等到所有要使用的图像都已加载后再进行绘制。使用它们的 onload 事件和/或
$(window).load()
或jQuery(document).ready
等。其他一些注意事项:
First question to ask yourself:
If you draw it repeatedly, say every 100 milliseconds, does the problem go away?
If no, the "drawing in the wrong order" is something you are doing and not an async error. I suspect this might be the case.
Images may not draw, but nothing should draw in the wrong order, assuming your
draw
routine is correct and that you are redrawing everything each time. According to the canvas spec, a call to drawImage does nothing if the image isn't loaded, so incorrect stacking should be impossible unless it is the order of your own calls.In any case, you should wait until all of the images you are going to use have loaded before you draw. Use their onload events and/or
$(window).load()
orjQuery(document).ready
, etc.Some other notes: