为什么我的代码不工作时,t类似于MDN?(OOP)

Why is my code not working when t is similar to MDN? (OOP)

本文关键字:MDN 类似于 OOP 代码 我的 工作 为什么      更新时间:2023-09-26

这是MDN的球速度代码:

var ball = {
  x: 100,
  y: 100,
  vx: 5,
  vy: 2,
  radius: 25,
  color: 'blue',
  draw: function() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2, true);
    ctx.closePath();
    ctx.fillStyle = this.color;
    ctx.fill();
  }
};
function draw() {
  ctx.clearRect(0,0, canvas.width, canvas.height);
  ball.draw();
  ball.x += ball.vx;
  ball.y += ball.vy;
  raf = window.requestAnimationFrame(draw);
};
canvas.addEventListener('mouseover', function(e){
  raf = window.requestAnimationFrame(draw);
});
ball.draw();

我的代码在这里:

var Ball = function(x, y, vx, vy, r, color) {
  this.x = x;
  this.y = y;
  this.vx = vx;
  this.vy = vy;
  this.radius = r;
  this.color = color;
  this.draw = function() {
    ctx.beginPath();
    ctx.arc(x, y, r, 0, Math.PI * 2, true);
    ctx.closePath();
    ctx.fillStyle = color;
    ctx.fill();
  }
};
function movement() {
  pingPong.draw();
  pingPong.x += pingPong.vx;
  pingPong.y += pingPong.vy;
  raf = window.requestAnimationFrame(movement);
};
canvas.addEventListener('mouseover', function(e){
  raf = window.requestAnimationFrame(movement);
});
var pingPong = new Ball(100, 100, 5, 1, 15, 'black');
pingPong.draw();

我不明白为什么我的球没有被重画。对我来说,它们看起来完全一样,我已经console.log了我的x和y坐标,它们正在更新。谁能告诉我为什么我的坏了?

MDN's

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

ctx.arc(x, y, r, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fillStyle = color;

在你的代码中,你没有加上this.,这可能会使你的对象没有颜色,并被放置在屏幕之外。