遇到了javascript画布图形和运动的问题



我正在创建一个JavaScript画布游戏,遇到了一个问题。我通过更改对象的位置、清除画布,然后重新绘制对象来创建运动。对于我提供的代码,ball 元素移动正常,但当矩形移动时,不会删除前一个元素。这会导致在屏幕上绘制一条线。如果有人看到我需要修复的内容,请告诉我。

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var p1;
var p2;
var ball;
p1 = new rectangle(10, 120, "black", 10, 120);
p2 = new rectangle(10, 120, "black", 1180, 120);
ball = new circle(600, 580, 10, "blue");
function gameupdate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
movep1();
moveball();
}
function rectangle(width, height, color, x, y) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.color = color;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
function circle(x, y, r, color) {
this.x = x;
this.y = y;
this.r = r;
this.color = color;
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
ctx.fill();
ctx.stroke();
ctx.closePath();
}
function moveball() {
ball.y += -3;
ball.x += 3;
new circle(ball.x, ball.y, 10, "blue");
}
function movep1() {
p1.y += 1;
new rectangle(p1.x, p1.y, "black", p1.width, p1.height);
}
setInterval(gameupdate, 10);
<canvas id="myCanvas"></canvas>

所以它在我的机器上工作正常,但是,您可能使用的是较旧的浏览器,因此请使用canvas.width = canvas.width清除画布以及ctx.clearRect()。我还注意到你试图创建一个类,但它更像是一个函数,所以我把它变成了一个类。

我建议你使用 ES6 类,因为它们使生活变得更加轻松,并使代码更加干净。以下是一些开始学习 ES6 课程的地方:

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
  • https://googlechrome.github.io/samples/classes-es6/
  • https://www.youtube.com/watch?v=2wWq6e6jz0g

代码如下:

var canvas = document.getElementById('ctx');
var ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var p1;
var p2;
var ball;
p1 = new Rectangle (10,120, "black", 10, 120);
p2 = new Rectangle (10, 120, "black", 1180, 120);
ball = new Circle (600,580,10,"blue");
function gameupdate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas.width = canvas.width;
movep1();
moveball();
drawAll();
}
function Rectangle (width,height,color,x,y) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.color = color;
this.draw = function(){
ctx.fillStyle = color;
ctx.fillRect(this.x,this.y,this.width,this.height);
}  
return this;
} 
function Circle (x,y,r,color) {
this.x = x;
this.y = y;
this.r = r;
this.color = color;
this.draw = function(){
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.r,0, 2* Math.PI);
ctx.fill();
ctx.stroke();
ctx.closePath();
}

return this;
}
function moveball () {
ball.y += -3;
ball.x += 3;
}
function movep1 () {
p1.y += 1;
}
function drawAll() {
p1.draw();
p2.draw();
ball.draw();
}
setInterval(gameupdate,10);
#ctx {
			width: 100%;
			height: 100%;
		}
<canvas id="ctx" width="100%" height="100%"></canvas>

希望这有帮助!

最新更新