Question

I am trying to draw multiple images on canvas using for loop. For some reason it only displays image on last position.

<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.0.2.min.js"></script>
<div id="container"></div>
<script defer="defer">    
var stage = new Kinetic.Stage({
    container: 'container',
    width: 578,
    height: 200
});
var layer = new Kinetic.Layer();

// add the layer to the stage
stage.add(layer);

for (var i=0; i<5; i++) {
    var imageObj = new Image();
    imageObj.onload = function() { 
        var yoda = new Kinetic.Image({

            x: 100*i,
            y: 50,
            image: this,
            width: 106,
            height: 118
        });

        // add the shape to the layer
        layer.add(yoda);
        stage.draw();

    };
    imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/yoda.jpg';
}
</script>

JSFiddle

Was it helpful?

Solution

Problem is that you're reusing var imageObj inside a loop.

Before the first image has been loaded, imageObj is being overwritten in the next step through the loop.

So fully load imageObj outside the loop and add multiple yodas inside the loop like this:

A Demo: http://jsfiddle.net/m1erickson/uK4DW/

var imageObj = new Image();
imageObj.onload = function() {
    for (var i=0; i<5; i++) {
        var yoda = new Kinetic.Image({
            x: 100*i,
            y: 50,
            image:imageObj,
            width: 106,
            height: 118
        });
        layer.add(yoda);
        layer.draw();
    };
}
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/yoda.jpg';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top