Swap images in html every so often

1

to see if you can throw me a cable. I'm doing a web page and I want to make images go by every x time. What I have right now is:

JAVASCRIPT:

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


var i=0;
var imagenes = ["./img/banner1.jpeg","./img/banner2.jpg","./img/banner3.png"];
img = new Image ();


function dibujar(){ 
    img.src = imagenes[0];
    ctx.drawImage(img, 0, 0, 900, 260);

    if(i<2){
        i++;
    }
    else{
        i=0;}
    }//dibujar()

setInterval(dibujar,300);

HTML:

<script type="text/javascript" src="js/javascript.js"></script>

But the static image remains. Let's see if you can tell me the fault. Thank you very much!

    
asked by Miguel 23.03.2018 в 20:12
source

1 answer

1

Hi, I made you a small demo, the truth is I have not used canvas, but it can serve as a base, although it does not change much if you do it with the canvas.

HTML:

<img id="to_show" src="" width="300px" heigth="300px" alt="">

JS:

var pos=0;
var to_show = document.getElementById('to_show');
var imagenes = 
['https://www.google.es/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png','http://www.apicius.es/wp-content/uploads/2012/07/IMG-20120714-009211.jpg'];


function dibujar(pos ){
    //Cada vez que se llama esta funcion, vamos mostrando la imagen de la posicion que nos pasa.
    to_show.src = imagenes[pos-1];
}


var to = setInterval(function(){
    pos++;
    dibujar(pos);
  //SI la variable que vamos incrementando es igual que la longitud de nuestro array, limpiamos el intervalo.
  if(pos == imagenes.length){
    clearInterval(to);
  }
},1000);

DEMO

    
answered by 23.03.2018 / 20:32
source