How to efficiently prevent images in javascript?

Asked

Viewed 57 times

0

I wanted to know if there is any function, some library or anything that facilitates the prevention of images. Is this what requirejs is for? I’m doing so at the moment:

var imgs = [];
imgs["cartas"] = [];
imgs["cartas"]["ouros"] = [];
imgs["cartas"]["espadas"] = [];
imgs["cartas"]["copas"] = [];
imgs["cartas"]["paus"] = [];
imgs["cartas"]["versos"] = [];
imgs["cartas"]["versos"]["azul"] = [];
imgs["cartas"]["versos"]["verde"] = [];
imgs["cartas"]["versos"]["vermelho"] = [];
for (var i = 0; i < 10; i++) {
    imgs["cartas"]["ouros"].push(loadImg(`img/cartas/ouros/carta${i}.png`));
    imgs["cartas"]["espadas"].push(loadImg(`img/cartas/espadas/carta${i}.png`));
    imgs["cartas"]["copas"].push(loadImg(`img/cartas/copas/carta${i}.png`));
    imgs["cartas"]["paus"].push(loadImg(`img/cartas/paus/carta${i}.png`));
    if (i > 0 && i < 6) {
        imgs["cartas"]["versos"]["azul"].push(loadImg(`img/cartas/versos/azul${i}.png`));
        imgs["cartas"]["versos"]["verde"].push(loadImg(`img/cartas/versos/verde${i}.png`));
        imgs["cartas"]["versos"]["vermelho"].push(loadImg(`img/cartas/versos/vermelho${i}.png`));
    }
}

2 answers

0

Here’s a simple function to pre-load your images

always liked this particular case is simple.

All your images will be stored on array images.

var images = [];
function preload() {
    for (var i = 0; i < arguments.length; i++) {
        images[i] = new Image();
        images[i].src = preload.arguments[i];
    }
}

// exemplo como usar
preload(
    "http://meusite.com/img/001.jpg",
    "http://meusite.com/img/002.jpg",
    "http://meusite.com/img/003.jpg"
)

Learn more

0

I’ve been doing some research and saw that there is no magic function to load images in javascript what I did was just this:

var imgs = [];
imgs["versos"] = [];
for (var i = 0; i < 10; i++) {
    imgs[`ouros${i}`] = (new Image()).src = `img/cartas/ouros/carta${i}.png`;
    imgs[`espadas${i}`] = (new Image()).src = `img/cartas/espadas/carta${i}.png`;
    imgs[`copas${i}`] = (new Image()).src = `img/cartas/copas/carta${i}.png`;
    imgs[`paus${i}`] = (new Image()).src = `img/cartas/paus/carta${i}.png`;
    if (i > 0 && i < 6) {
        imgs["versos"][`azul${i}`] = (new Image()).src = `img/cartas/versos/azul${i}.png`;
        imgs["versos"][`verde${i}`] = (new Image()).src = `img/cartas/versos/verde${i}.png`;
        imgs["versos"][`vermelho${i}`] = (new Image()).src = `img/cartas/versos/vermelho${i}.png`;
    }
}

It’s gotten a little better.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.