堆叠画布和像素操作哪个更快?

发布于 2024-12-11 06:39:41 字数 577 浏览 0 评论 0原文

我正在使用一些 HTML 5 功能制作一个小型俄罗斯方块克隆,但我遇到了一些进退两难的情况。

我的四格骨牌不是由块组成的——它们有取决于旋转的阴影和阴影,因此每个都是它自己的图像。这意味着我不能在每次游戏状态发生变化时使用正常的“重画所有内容”,因为这意味着跟踪所有棋子掉落历史并在我想要清除一条线时“重播”它。

所以我的选择是:

1)创建两个彼此堆叠的画布元素。背面是“板”图像。上面的一块是画布,我可以在其中轻松地切片和重新排列东西。不过,这感觉很黑客,因为我想将所有内容都保留在一个画布元素中。

2)创建“绘图”上下文和“缓冲区”上下文。在缓冲区上下文中,我拥有所有部分并且可以自由操作它,当需要将缓冲区绘制到屏幕上时,我获取ImageData,循环遍历所有像素,并将它们合成到棋盘图像上。然后我使用 putImageData 将其写入“绘图”上下文中。出现这种麻烦是因为我找不到一种方法来获取 ImageData 结构并将其合成到画布元素上(您可以使用 drawImage 通过 ImageElements 来做到这一点,但 drawImage 不会采用 ImageData 结构)。

对我来说,这两种解决方案都显得非常优雅。

谢谢

I'm making a little Tetris clone using some of the HTML 5 features, and I've come to a bit of a dilemma.

My tetrominos aren't composed of blocks -- they have shading and shadows that depend on the rotation and thus each is its own image. Which means I can't use the normal "redraw everything" every time the game state changes, because that would mean keeping track of all the piece drop history and "replaying" it whenever I want to clear a line.

So my options are:

1) Create two canvas elements stacked upon each other. The one on the back is the "board" image. The one on top is the pieces canvas, where I can slice and rearrange things easily. This feels very hackish though, as I wanted to keep everything in one canvas element.

2) Create a "drawing" context and a "buffer" context. In the buffer context, I have all of the pieces and can manipulate it freely, and when it's time to draw the buffer to the screen, I getImageData, loop through all of the pixels, and composite them onto the board image. I then write this into the "drawing" context with putImageData. This hassle occurs because I can't find a way to take an ImageData structure and composite it onto a canvas element (you can do that with ImageElements using drawImage, but drawImage won't take an ImageData structure).

Neither solution seems very elegant to me.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柠檬色的秋千 2024-12-18 06:39:41

分层画布并没有什么“黑客”之处。

类似的策略在许多系统中的多个层面上执行,从旧的投币游戏机到现代 GPU,甚至 80 年代的 8 位家用计算机,更不用说经典的手绘卡通了(使用类似技术在透明醋酸纤维上绘制)。

事实上,即使您进行其他类型的操作,出于多种原因,您也很可能应该进行分层。

There's nothing 'hackish' about layering canvases.

Similar strategies are performed at several level in many systems from old coin-operated consoles to modern GPUs, passing though 80's 8bit home computers, and that's without mentioning classic hand-drawn cartoons (which were drawn on transparent acetate to use similar techniques).

in fact, even if you do other kinds of manipulation, it's quite likely you should do layering for lots of reasons.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文