堆叠画布和像素操作哪个更快?
我正在使用一些 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
分层画布并没有什么“黑客”之处。
类似的策略在许多系统中的多个层面上执行,从旧的投币游戏机到现代 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.