Анимация объектов, назначенных массиву в JavaScript - PullRequest
0 голосов
/ 03 мая 2018

Я пытаюсь оживить некоторые квадраты, чтобы они появлялись в разные моменты, но я достигаю только рисования и анимации одного квадрата. Я пытаюсь назначить квадраты в массив, но не анимировать. Я хочу сделать что-то вроде графического интерфейса Guitar Hero. Я пытаюсь заставить некоторые квадраты двигаться вниз по оси Y, меняя их положение и рисуя их в определенное время. Буду признателен, если вы поможете мне.

<canvas id="myCanvas" width="1000" height="600"></canvas> 

<script>

void function(){    

"use strict";

    alert('Comienza el Juego');


    //Global Vars

    var startTime = (new Date()).getTime();
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    var YellowArray = [];
    var RedArray = [];
    var len = 5;
    var i,j;

    //Assigning 5 squares into the array
    for (i=0;i<len;i++){

        var items = YellowArray.push({      
                x: 171,
                y: 100,     //Da igual el valor que se le de aqui
                width: 60,
                height: 60,
                color: "yellow"     
        }); 
    }


    //Objects used to draw the squares

    var YellowSquareFixed = {
            x: 160,
            y: 465,     //Da igual el valor que se le de aqui
            width: 80,
            height: 80,
            color: "yellow"
    };


    var YellowSquareMove2 = {
            x: 160,
            y: 200,     //Da igual el valor que se le de aqui
            width: 60,
            height: 60,
            color: "yellow"
    };


    var YellowSquareMove = {
            x: 160,
            y: 200,     //Da igual el valor que se le de aqui
            width: 60,
            height: 60,
            color: "yellow"
    };


    var RedSquareMove = {
            x: 321,
            y: 200,     //Da igual el valor que se le de aqui
            width: 60,
            height: 60,
            color: "red"
    };

    var RedSquareFixed = {
        x: 310,
        y: 465,
        width: 80,
        height: 80,
        color: "red"
    };



    var OrangeSquareFixed = {
        x: 460,
        y: 465,
        width: 80,
        height: 80,
        color: "#F34621"
    };



    var BlueSquareFixed = {
        x: 610,
        y: 465,
        width:  80,
        height: 80,
        color: "blue"
    };



    var GreenSquareFixed = {
        x: 760, 
        y: 465,
        width: 80,
        height: 80,
        color: "green"
    };


    //Function used to draw the lines of the game (not important)
    function DrawingLines(x1, y1, x2, y2, color) {  

        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;


        ctx.fillStyle = color;
        ctx.lineWidth="2";
        ctx.strokeStyle="black";
        ctx.moveTo(this.x1,this.y1);
        ctx.lineTo(this.x2,this.y2);
        ctx.stroke();   

    }

    //Function used to draw the fixed element of the game
    function lienzo (){

        new DrawingLines(200, 0, 200, 600, "black");
        new DrawingLines(350, 0, 350, 600, "black");
        new DrawingLines(500, 0, 500, 600, "black");
        new DrawingLines(650, 0, 650, 600, "black");
        new DrawingLines(800, 0, 800, 600, "black");

        new FinalLine(100, 500, 800, 20, "purple");

        DrawingFixedSquares(YellowSquareFixed, ctx);  
        DrawingFixedSquares(RedSquareFixed, ctx);
        DrawingFixedSquares(OrangeSquareFixed, ctx);
        DrawingFixedSquares(BlueSquareFixed, ctx);
        DrawingFixedSquares(GreenSquareFixed, ctx);

    }


    //Function used to draw the squares
    function DrawingFixedSquares(myRectangle, ctx) {  
            ctx.fillStyle = myRectangle.color;
            ctx.fillRect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height);  

    }


    //Función which draws the final line of the game
    function FinalLine(x, y, width, height, color) {  

        this.height = height;
        this.width = width;
        this.x = x;
        this.y = y;
        ctx.fillStyle = color;
        ctx.fillRect(this.x, this.y, this.width, this.height);

    }


    //Principal function of the game. It draws and animate the square,  
    //refreshing its position
    function animate(Array) {

    // update
    //tiempo que transcurre desde el 1/1/1990 hasta el momento en que se ejecuta
    var time = (new Date()).getTime() - startTime;

    var linearSpeed = 700;

    //pixels / second
    var newY = linearSpeed * time / 1000;

    if(newY < 487) {
      Array[0].y = newY;
    }


    ctx.clearRect(0, 0, canvas.width, canvas.height);

    lienzo();   
    new DrawingFixedSquares(Array[0], ctx);

        //request new frame
        requestAnimationFrame(function(){

            animate(Array)
        }); 
    }


    //Function used to call the function animate

    function Cuadrados () { 

        animate(YellowArray);
    }



    //Starting function
    window.onload = function (){

        lienzo();
        Cuadrados ();   

    }

 }();
    </script>

</body>
</head>

1 Ответ

0 голосов
/ 04 мая 2018

Посмотрите эту скрипку, как сделать квадраты из класса, чтобы сделать ваш код более простым и понятным. Все они используют одинаковые методы обновления и рисования:

https://jsfiddle.net/mulperi/a94ktd6L/

В демоверсии все они имеют разные скорости, но вы можете добавить свою собственную логику к времени.

Обычно вы просто вызываете методы отрисовки и обновления следующим образом:

// All the drawing stuff and clearing the screen goes here
function draw() {
  ctx.clearRect(0, 0, c.width, c.height);
  squares.forEach(square => square.draw());
}

// The "game loop", all the update stuff goes here
function update() {
  draw();
  squares.forEach(square => square.update());
  requestAnimationFrame(update);
}
requestAnimationFrame(update);

Надеюсь, это поможет вам! :)

...