clearRect不工作 [英] clearRect not working
问题描述
我在javascript做一个乒乓球游戏,以学习制作游戏,我想让它面向对象。
我不能得到 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 ++;
}
我试图把 ctx.clearRect
和部分在
draw()
和 t工作。
我也尝试了 fillRect
与白色,但它给出相同的结果。
我如何解决这个问题?
$ b
在绘制圆圈之前添加 ctx.beginPath()
$ b
jsFiddle 。
此外,提示...
- 您的资产不应负责绘制自己(他们的
draw $ c> method)。相反,也许定义他们的视觉属性(是一个圆?半径?),让你的主要渲染函数处理
canvas
特定的绘图(这也有优点, - 而不是
setInterval()
,请使用requestAnimationFrame()
。支持目前不是那么好,所以你可能想要使用setInterval()
或递归setTimeout()$ c $ c> pattern。
- 您的
clearRect()
$ c>元素(或将它们定义在某处)。将它们包含在渲染函数中类似于魔术数字,可能会导致维护问题进一步向下。
I'm doing a Pong game in javascript in order to learn making games, and I want to make it object oriented.
I can't get clearRect
to work. All it does is draw a line that grows longer.
Here is the relevant code:
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?
Your real problem is you are not closing your circle's path.
Add ctx.beginPath()
before you draw the circle.
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 numbers and could lead to a maintenance issue further down the track.
这篇关于clearRect不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!