问题
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