Плавное движение объекта по диагонали с разными высотой и шириной JS canvas

57
20 января 2022, 01:50

При клике создаётся объект, после движется к координатам клика. Необходимо сделать плавное движение по диагонали. Сейчас может произойти такая ситуация, что сначала объект дойдёт до конца по Y, а потом идёт по X.

var canvas = document.getElementById("canvas"); 
var ctx = canvas.getContext("2d"); 
canvas.width = window.innerWidth; 
canvas.height = window.innerHeight; 
 
var bullets = []; 
 
function Bullet(x, y, r, endX, endY) { 
  this.x = x; 
  this.y = y; 
  this.r = r; 
  this.endX = endX; 
  this.endY = endY; 
 
  this.draw = function() { 
    ctx.beginPath(); 
    ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false); 
    ctx.fill(); 
 
    if (this.x + 5 < this.endX) { 
 
      this.x += 5; 
    } else { 
      this.x -= 5; 
    } 
    if (this.y + 5 < this.endY) { 
      this.y += 5; 
    } else { 
      this.y -= 5; 
    } 
  } 
} 
 
function animate() { 
  requestAnimationFrame(animate); 
  ctx.clearRect(0, 0, canvas.width, canvas.height); 
  ctx.fillStyle = '#000'; 
  ctx.arc(800, 350, 10, 0, Math.PI * 2, false); 
  ctx.fill(); 
 
  for (let bullet of bullets) { 
    bullet.draw(); 
  } 
} 
 
window.onclick = function(e) { 
  bullets.push(new Bullet(800, 350, 10, e.pageX, e.pageY)); 
} 
 
animate();
#canvas { 
  border: 1px solid black; 
  width: 100%; 
  height: 100%; 
}
<canvas id="canvas"></canvas>

Answer 1

var canvas = document.getElementById("canvas"); 
var ctx = canvas.getContext("2d"); 
canvas.width = window.innerWidth; 
canvas.height = window.innerHeight; 
 
var bullets = []; 
 
function Bullet(x, y, r, endX, endY) { 
  this.x = x; 
  this.y = y; 
  this.r = r; 
  this.endX = endX; 
  this.endY = endY; 
 
  this.draw = function() { 
    ctx.beginPath(); 
    ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false); 
    ctx.fill(); 
     
    if (this.x != this.endX || this.y != this.endY) { 
      var dx = this.endX - this.x; 
      var dy = this.endY - this.y; 
      var d = Math.sqrt(dx*dx + dy*dy); 
      if (d <= 5) { 
        this.x = this.endX; 
        this.y = this.endY; 
      } else { 
        this.x += 5 * dx / d; 
        this.y += 5 * dy / d; 
      } 
    } 
  } 
} 
 
function animate() { 
  requestAnimationFrame(animate); 
  ctx.clearRect(0, 0, canvas.width, canvas.height); 
  ctx.fillStyle = '#000'; 
  ctx.arc(800, 350, 10, 0, Math.PI * 2, false); 
  ctx.fill(); 
 
  for (let bullet of bullets) { 
    bullet.draw(); 
  } 
} 
 
window.onclick = function(e) { 
  bullets.push(new Bullet(0, 0, 5, e.pageX, e.pageY)); 
} 
 
animate();
#canvas { 
  border: 1px solid black; 
  width: 100%; 
  height: 100%; 
}
<canvas id="canvas"></canvas>

READ ALSO
Проверить на заполненность

Проверить на заполненность

Как одним условием проверить на заполненность все поля ввода?

96