HTML5 Remove previous drawn object in canvas(HTML5 删除画布中先前绘制的对象)
问题描述
借助 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 删除画布中先前绘制的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:HTML5 删除画布中先前绘制的对象
基础教程推荐
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01