Попытка нарисовать несколько скворов (Javascript) - PullRequest
1 голос
/ 26 апреля 2020

Я только начинаю изучать вещи самостоятельно в JS, не используя учебники! Я пытаюсь сделать простую вещь из нескольких красных квадратов, падающих с вершины холста на дно. Другое правило, которое я хотел применить, - это когда программа начинается - х позиция квадрата выбирается случайным образом. Пока мне удалось создать один квадрат. Есть ли способ, чтобы l oop мой объект "враг" (квадрат) несколько раз! (Код указан ниже)

спасибо!

var cvs = document.getElementById("canvas");
var ctx = cvs.getContext("2d");


var enemy = {
    h: 20,
    w: 20,
    x: 250,
    y: 0,
    speed: 5,
    draw: function(){
        ctx.fillStyle = "#ff0000"
        ctx.beginPath();
        ctx.fillRect(this.x, this.y, this.w, this.h)
        ctx.fill();
    },
    logic: function(){
        if(enemy.y > cvs.height){
            enemy.y = -cvs.height
        }
    }
}

function draw(){
    for (var i = 1; i < 8; i++) {
        enemy.draw(i);}
}

function loop(){

    enemy.y += enemy.speed
    ctx.fillStyle = "#202020"
    ctx.fillRect(0, 0, 500, 500)
    enemy.logic()

    draw();
    requestAnimationFrame(loop);
}

loop();

1 Ответ

0 голосов
/ 26 апреля 2020

Поскольку вы начинаете с canvas, я рекомендую вам использовать классы. Go через комментарии, чтобы вы все поняли, и сами опробовали новые вещи.

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

const squares = []; // make an array where squares will be stored

function Square(h, w, x, y, speed) {
    // this.h is referencing to a single square's height
    // h is the passed argument
    // it goes like this for all of the properties a single square needs
    // classes like this always require this type of defining
    this.h = h;
    this.w = w;
    this.x = x;
    this.y = y;
    this.speed = speed;


    this.draw = function() {
        ctx.fillStyle = "#ff0000"
        ctx.beginPath();
        ctx.fillRect(this.x, this.y, this.w, this.h)
        ctx.fill();
    };

    this.animate = function() {
        this.y += this.speed; // movement

        if (this.y > cvs.height) { // restart on top if the square fell entirely down
            this.y = -cvs.height;
        }

        this.draw(); // draw a square after the "movement" changed it's position
    };
}

for (let i = 0; i < 5; i++) {
    let h = 20;
    let w = 20;
    let x = Math.floor(Math.random() * cvs.width); // random position from the available canvas width
    let y = 0;
    let speed = 5;
    // now pass all of those made arguments
    squares.push(new Square(h, w, x, y, speed)); // push these values to the array of squares TROUGH the class
}


function Update() {
    ctx.clearRect(0, 0, cvs.width, cvs.height); // clear the canvas before drawing new squares

    for (let i = 0; i < squares.length; i++) {
        squares[i].animate(); // animate every square in the array of squares
    }

    requestAnimationFrame(Update); // recursive animation function
}

Update(); // start animating

function Square(h, w, x, y, speed) {...} - это класс

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...