javascript clearRect 不工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9743027/
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
clearRect not working
提问by justanotherhobbyist
I'm doing a Pong game in javascript in order to learn making games, and I want to make it object oriented.
我正在用 javascript 做 Pong 游戏以学习制作游戏,我想让它面向对象。
I can't get clearRect
to work. All it does is draw a line that grows longer.
Here is the relevant code:
我不能clearRect
上班。它所做的只是画一条越来越长的线。这是相关的代码:
function Ball(){
this.radius = 5;
this.Y = 20;
this.X = 25;
this.draw = function() {
ctx.arc(this.X, this.Y, this.radius, 0, Math.PI*2, true);
ctx.fillStyle = '#00ff00';
ctx.fill();
};
}
var ball = new Ball();
function draw(){
player.draw();
ball.draw();
}
function update(){
ctx.clearRect(0, 0, 800, 400);
draw();
ball.X++;
}
I've tried to put the ctx.clearRect
part in the draw()
and ball.draw()
functions and it doesn't work.
I also tried fillRect
with white but it gives the same results.
How can I fix this?
我试图把这个ctx.clearRect
部分放在draw()
和ball.draw()
函数中,但它不起作用。我也试过fillRect
白色,但它给出了相同的结果。我怎样才能解决这个问题?
回答by alex
Your realproblem is you are not closing your circle's path.
你真正的问题是你没有关闭你圈子的路径。
Add ctx.beginPath()
before you draw the circle.
ctx.beginPath()
在画圆之前添加。
Also, some tips...
还有一些小窍门...
- Your assets should not be responsible for drawing themselves (their
draw()
method). Instead, perhaps define their visual properties (is it a circle? radius?) and let your main render function handlecanvas
specific drawing (this also has the advantage that you can switch your renderer to regular DOM elements or WebGL further down the track easily). - Instead of
setInterval()
, userequestAnimationFrame()
. Support is not that great at the moment so you may want to shim its functionality withsetInterval()
or the recursivesetTimeout()
pattern. - Your
clearRect()
should be passed the dimensions from thecanvas
element (or have them defined somewhere). Including them in your rendering functions is akin to magic numbersand could lead to a maintenance issue further down the track.
- 您的资产不应该负责绘制自己(他们的
draw()
方法)。相反,也许可以定义它们的视觉属性(它是圆吗?半径?)并让您的主渲染函数处理canvas
特定的绘图(这也有一个优点,您可以轻松地将渲染器切换到常规 DOM 元素或 WebGL 更进一步)。 - 而不是
setInterval()
,使用requestAnimationFrame()
。目前支持不是很好,因此您可能希望使用setInterval()
递归setTimeout()
模式填充其功能。 - 您
clearRect()
应该从canvas
元素传递尺寸(或在某处定义它们)。将它们包含在您的渲染函数中类似于幻数,可能会导致后续的维护问题。