Как мне сделать так, чтобы я мог анимировать много шаров в функции рисования в Java Script? - PullRequest
0 голосов
/ 07 ноября 2019

Я пытаюсь запустить свой код, чтобы на экране появилось несколько шариков. После отладки я обнаружил, что мои переменные circleX и circleY не отображаются в моем коде. circlX - это расположение шара, который я хочу CircleX и circleY , переданного в drawManyBalls и drawBallsMoving .

Я не уверен, почему он не запускает мой код или не видит эти переменные.

Я пытался использовать метод apply, чтобы попытаться применить circlX и circleY переменные, где я запускаю эту функцию, а затем применяю ее к другой функции. как видно в этой ссылке .

Я также пытался запустить функцию внутри функции, но это не сработало.

проверьте мой код на Js Fiddle: https://jsfiddle.net/Blummer92/kuj2tzy4/1/

Java Script

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

//every frame has been drawn to make it appear that the ball is moving
//this sets the moving ball
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

//every frame has been drawn to make it appear that the ball is moving
//this sets the moving ball
let circleX = canvas.width / 2;
let circleY = canvas.height - 30;
var ballRadius = 10;

// newly spawned objects start at Y=25
var spawnLineY = 25;

// spawn a new object every 1500ms
var spawnRate = 1500;

// set how fast the objects will fall
var spawnRateOfDescent = 0.5;

// when was the last object spawned
var lastSpawn = -1;

// this array holds all spawned object
var objects = [];

// save the starting time (used to calc elapsed time)
var startTime = Date.now();

var dx =2;
var dy =-2;

function spawnRandomObject(object) {

    // select a random type for this new object
    var t;

    // About Math.random()
    // Math.random() generates a semi-random number
    // between 0-1. So to randomly decide if the next object
    // will be A or B, we say if the random# is 0-.49 we
    // create A and if the random# is .50-1.00 we create B

    if (Math.random() < 0.50) {
        t = "red";
    } else {
        t = "blue";
    }

    // create the new object
    var object = {
        // set this objects type
        type: t,
        // set x randomly but at least 15px off the canvas edges
        x: Math.random() * (canvas.width - 30) + 15,
        // set y to start on the line where objects are spawned
        y: spawnLineY,
    }

    // add the new object to the objects[] array
    objects.push(object);
}

let drawBall = (circleX, circleY) => {
  ctx.beginPath();
  let dimentions = ballRadius => {
    ctx.arc(circleX, circleY, ballRadius, 0, Math.PI * 2);

    ctx.fillStyle = "#0095DD";
    ctx.fill();

    ctx.closePath();
  };

var drawManyBall = () => {
    let CircleX = spawnRandomObject.object.X;
    let CicleY = spawnRandomObject.object.Y;
    drawBall();
    drawBall.dimentions.apply(this, circleX, circleY); // use .apply() to call it
    ctx.moveTo(circleX, circleY + spawnLineY);
    ctx.lineTo(canvas.width, spawnLineY);
  };
let draw = () => {
  circleX += dx;
  circleY += dy;

// get the elapsed time
var time = Date.now();

// see if its time to spawn a new object
if (time > lastSpawn + spawnRate) {
  lastSpawn = time;
  spawnRandomObject();
}

// request another animation frame
requestAnimationFrame(draw);

ctx.clearRect(0, 0, canvas.width, canvas.height);
// runs a loop that
for (var i = 0; i < objects.length; i++) {
  var object = objects[i];

  //should I be using cirlce why as a part of my method?
  object.Y += spawnRateOfDescent;
  let CircleX = object.X;
  let CicleY = object.Y;

  var drawBallsmoving = () => {
    drawBall();
    drawBall.dimentions.apply(this, circleX, circleY);
    ctx.beginPath();
    ctx.arc(object.x, object.y, 8, 0, Math.PI * 2);
    ctx.fillStyle = object.type;
  };
}

Во время отладки мой вывод был

drawBall: (circleX, circleY) => {…}
arguments: [Exception: TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them at Function.invokeGetter (<anonymous>:1:142) at <anonymous>:1:1]
caller: [Exception: TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them at Function.invokeGetter (<anonymous>:1:142) at <anonymous>:1:1]
length: 2
...