Html HTML5 删除画布中先前绘制的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16969787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 09:11:05  来源:igfitidea点击:

HTML5 Remove previous drawn object in canvas

javascripthtmlhtml5-canvas

提问by Anish

I have a polygon object (say a car) drawn inside a HTML5 canvas with help of methods moveToand 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?

我在 HTML5 画布中借助方法moveTolineTo. 我想在画布中的不同位置重复绘制该对象(模拟移动对象)。我的问题是之前绘制的对象没有被清除。相反,在画布上绘制了多个图像。我该如何解决这个问题?

回答by Tom

You have to clear the canvas at the start of every draw frame

您必须在每个并条框开始时清除画布

context.clearRect(0, 0, canvas.width, canvas.height);

回答by Alnitak

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.

有一些动画技巧曾经用于位图显示(例如“异或绘图”),可用于在绘制新形状之前删除旧形状,但在现代机器上通常要简单得多(并且非常快)擦除画布并重新开始每一帧。

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.

鉴于您对其他答案的评论,我建议只使用两个画布 - 一个用于静态背景,一个用于汽车。如果背景图像是静态的,它甚至可以是一个<img>元素而不是 Canvas。

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.

如果汽车图像是静态的,您也可以只绘制一次,然后使用 CSS 定位来设置其相对于每一帧背景的位置。