借助 moveTo
和 lineTo
方法,我在 HTML5 画布内绘制了一个多边形对象(比如汽车).我想在画布的不同位置重复绘制该对象(模拟移动对象).我的问题是之前绘制的对象没有被清除.相反,在画布上绘制了多个图像.我该如何解决这个问题?
I have a polygon object (say a car) drawn inside a HTML5 canvas with help of methods moveTo
and lineTo
. I want to repeatedly draw that object at different positions in the canvas (simulating a moving object). My problem is that the previous drawn object is not getting cleared. Instead, multiple images are drawn on the canvas. How can I fix this issue?
画布只是像素数组,它们对你绘制的形状一无所知.
Canvases are just arrays of pixels, they know nothing of the shapes you have drawn.
过去在位图显示器上使用了一些动画技巧(例如异或绘图"),可用于在绘制新形状之前移除旧形状,但在现代机器上通常要简单得多(而且速度非常快) 只是擦除画布并为每一帧重新开始.
There are animation tricks that used to be used on bitmapped displays (e.g. "xor drawing") that can be used to remove the old shape before you draw the new one, but on modern machines it's generally far simpler (and perfectly fast) to just erase the canvas and start again for each frame.
鉴于您对其他答案的评论,我建议只使用两个画布 - 一个用于静态背景,一个用于汽车.如果背景图片是静态的,它甚至可以是 <img>
元素而不是 Canvas.
Given your comments to other answers, I'd suggest just using two Canvases - one for the static background and one for the car. If the background image is static it could even be an <img>
element instead of a Canvas.
如果汽车图像是静态的,您也可以只绘制一次,然后使用 CSS 定位设置其相对于每一帧背景的位置.
If the car image is static you could also just draw that once, and then use CSS positioning to set its position relative to the background for each frame.
这篇关于HTML5 删除画布中先前绘制的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!