如何在JavaScript画布中使矩形位于所有其他矩形之上? [英] How can I make a rectangle be on top of all other rectangles in javascript canvas?

查看:53
本文介绍了如何在JavaScript画布中使矩形位于所有其他矩形之上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含菜单的矩形。我需要此矩形位于游戏中所有其他对象的顶部。请记住,没有CSS,只有javascript canvas编程。
我该怎么做?

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);

这就是我想知道的。

推荐答案

画布本身没有内置的分层。但是您有多种选择:

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


  • 在HTML文档中添加第二个画布,并使用CSS定位将其放置在另一个画布上画布对象。在上部画布上绘制矩形,在下部画布上绘制其他任何内容。上方画布上的所有透明像素都将显示下方画布的内容。

  • 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.

使用绘制循环,在其中使用 window.requestAnimationFrame 擦除并重新绘制整个场景(无论如何,足够复杂的游戏通常都会在那里结束迟早)。按照希望它们重叠的顺序绘制对象,这意味着您最后绘制了矩形。

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.

这篇关于如何在JavaScript画布中使矩形位于所有其他矩形之上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆