tlengman
tlengman

Reputation: 3

When to load an image to use the Javascript function drawImage()?

I would like to use the drawImage() function to load an image in a Javascript animation, but the image does not load with my current code. I think I need to specifically ask for the image to be loaded at some point, but I'm not sure when or how. The idea is to make a cloud that goes across the canvas. Thank you for your help.

function draw(x,y){
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    x += 2;
    if(x>1000){
        x=0;
    }

    var cloud = new image();
    cloud.src='small_cloud.png';
    ctx.drawImage(cloud,x,0);

    var loopTimer = setTimeout('draw('+x+','+y+')',20);

}

Upvotes: 0

Views: 531

Answers (1)

Peter Herdenborg
Peter Herdenborg

Reputation: 5962

Try new Image()rather than new image()

Also move

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');    
var cloud = new image();
cloud.src='small_cloud.png';

to outside the draw()function, as you only want to set these things up once. Delay this setting up until the browser has had time to parse the document, for example using

window.onload = function(){ ... };

(Though in reality you'd have to make sure not to overwrite any existing window.onload listeners by using proper even handler registration.) Also delay the first invocation to draw()until the image has loaded, for example like so:

cloud.onload = function(){
    draw(cloud, 0, 0);
}

I'd also change

var loopTimer = setTimeout('draw('+x+','+y+')',20);

to

setTimeout(function(){ draw(x, y); }, 20);

since you seem not to be using the loopTimer variable, and since passing setTimeout an anonymous function rather than a string is considered better practice.

Finally, it would look like this:

window.onload = function() {
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');    
    var cloud = new image();
    cloud.src='small_cloud.png';    
    cloud.onload = function(){
        draw(ctx, cloud, 0, 0);
    };
};

function draw(ctx, cloud, x,y){
    x += 2;
    if(x>1000){
        x=0;
    }

    ctx.drawImage(cloud,x,0);

    setTimeout(function(){ draw(ctx, cloud, x, y); }, 20);
}

Note that, since ctx is no longer defined inside the draw() function, as it is local to the anonymous window.onload function, you also has to pass ctx to the draw() function.

Upvotes: 2

Related Questions