开发者

How can I clear the previous position of the circle in my canvas?

开发者 https://www.devze.com 2023-03-01 13:54 出处:网络
I\'m trying to make Pong using canvas with JavaScript. It has been many years since I made any game, and therefore am quite the beginner.

I'm trying to make Pong using canvas with JavaScript.

It has been many years since I made any game, and therefore am quite the beginner.

I have a problem where I am trying to move the ball (just its x position, for now) and trying to remove its previous position. The code I am using worked for the paddle (up and down keys to move it).

But, it doesn't seem to want to work with the ball.

What am I doing wrong?

thi开发者_Python百科s.draw = function() {
    ctx.clearRect(this.prevX - this.radius, this.prevY - this.radius, this.radius * 2, this.radius * 2);

    ctx.fillStyle = this.color;
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
    ctx.fill();

    this.prevX = this.x;
    this.prevY = this.y;
 }

jsFiddle.

I know I am using clearRect(), but I was under the impression it just removes a rectangular portion of the canvas.

clearRect(x,y,width,height) : Clears the specified area and makes it fully transparent

Source.

Feel free to give me any other tips too, as I'm pretty much a beginner with this.


It's actually because you are not calling beginPath, so every new circle you draw also redraws all of the old circles!

Fix here with illustration:

http://jsfiddle.net/UvGVb/15/

Take out the call to beginPath to see what was happening before.


I am no expert on canvas, so I will go with the "other tips too" plead. :-) If you step away from canvas and instead use html elements like div to draw your paddles and ball, you won't have to bother with removing, only moving. Then there are lots of libraries to help you with element positioning, animation etc, of which jQuery would be my first choice.


You might be giving incorrect coordinates to the 'clearrect' function when you render the new position of the ball. Some of your references to 'this' look like they might be dodgy too:

var that = this;

The above is inside a function - I think it is referencing 'this' in the local scope of the function rather than the scope of the ball (which is I assume what you intend). You can set up a reference to this (ball scope) and use that from inside inner functions if you need to.

Try printing out the coordinates of the ball, and the coordinates of its previous position. You can then work out whether or not you are clearing the right area of the canvas. I'd also check your use of the this keyword and make sure it's in the right scope for what you want to do.

I have only had a quick look so I'm sorry if I've misunderstood what you're trying to do.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号