Thomas Pereira
Thomas Pereira

Reputation: 239

how to make a variable of two variables

Before your read this, my first account was blocked because i asked bad questions.. So please dont vote negative but say what i am doing wrong

Sooo I have this script:

var img1 = new Image()
img1.src="image1.jpg"
var img2 = new Image()
img2.src="image2.jpg"
var img3 = new Image()
img3.src="image3.jpg"

function Canvas() {
    var ctx = document.getElementById('slider').getContext('2d');
    var pic=1

    function slider() {
        this.draw = function() {
            if(pic<4){pic++}
            else{
                pic=1
            }
            var img = "img"+pic
            ctx.drawImage(img,0,0,ctx.canvas.width,ctx.canvas.height)
        }
    }

    var slider = new slider();

    function draw() {
        ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
        ctx.save();
        //draw

        slider.draw();

        //draw
        ctx.restore();
    }

    var animateInterval = setInterval(draw,100) 
}

window.addEventListener('load', function(event) {
Canvas();
});

I am trying to draw the image 1 or 2 or 3 on my canvas. But I also have the var pic wich has the number. So i tried ctx.drawimage(img+pic,0,0) or var img = "img"+pic and draw it then. But it doesnt work for me.

I hope you accept my question and can answer it, THNX

Upvotes: 0

Views: 57

Answers (3)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

Use an array instead

var img = [];

/*  you should use a for loop here */
for (var i = 0; i < 3; i++) {
   img[i] = new Image();
   img[i].src = "image" + (i+1) ".jpg";
}

and later you refer the right image with img[pic]. Be only sure to use an index between 0 and img.length - 1

Upvotes: 1

Ragnar
Ragnar

Reputation: 543

The error seems to be that you refer to the string "img1" and not the object img1. Try use an array instead. Set the following:

...
var pic=0;
var img=[img1,img2,img3];

function slider() {
    this.draw = function() {
        if(pic<3){pic++}
        else{
            pic=0;
        }
        ctx.drawImage(img[pic],0,0,ctx.canvas.width,ctx.canvas.height)
    }
}
...

Upvotes: 1

Barmar
Barmar

Reputation: 782285

Don't use separate variables, use an array.

var images = [ new Image(), new Image(), new Image() ];
for (var i = 0; i < images.length; i++) {
    images[i].src = "image" + (i+1) + ".jpg";
}

Then refer to the array in the Slider() function:

var pic = 0;
function slider() {
    this.draw = function() {
        pic = (pic + 1) % images.length;
        var img = images[pic];
        ctx.drawImage(img,0,0,ctx.canvas.width,ctx.canvas.height)
    }
}

Upvotes: 1

Related Questions