How can I make a rectangle be on top of all other rectangles in javascript canvas?

情到浓时终转凉″ 提交于 2019-12-24 15:33:30

问题


I have a rectangle which includes the menu. I need this rectangle to be on top of all other objects in the game. Bear in mind, no css, just javascript canvas programming. How can I do that?

If you need any code about the rectangle:

ctx.fillRect(0,0,width,100);

That is all you need to know I guess.


回答1:


The canvas itself has no in-built layering. But you have multiple options:

  • Add a second canvas to your HTML document, and use CSS positioning to place it above the other canvas object. Draw your rectangle on the upper canvas and any other content on the lower canvas. Any transparent pixels on the upper canvas will show the content of the canvas below.

  • Redraw the rectangle after any other drawing operation.

  • Use a drawing loop where you erase and redraw the whole scene with window.requestAnimationFrame (any sufficiently complex game usually ends up there anyway sooner or later). Draw your objects in the order you want them to overlap, which means you draw said rectangle last.



来源:https://stackoverflow.com/questions/29319628/how-can-i-make-a-rectangle-be-on-top-of-all-other-rectangles-in-javascript-canva

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!