I'm starting to learn work with JavaScript and HTML5's canvas.
I'm trying to draw several elements with different patterns, but I'm getting always the last setted pattern. I tried to use save() and restore() methods to store stack stats but surely I'm making a mistake somewhere, can anybody help me?
window.onload = function(){
    draw(100, 100, "http://www.itexto.net/devkico/wp-content/uploads/2011/03/stackoverflow-logo-250.png");
    draw(0, 0, "http://googlediscovery.com/wp-content/uploads/google-home.png");            
};
function draw(x, y, src) {
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
    context.save();
    var imageObj = new Image();
    imageObj.onload = function(){
        var pattern = context.createPattern(imageObj, "repeat");
        context.rect(x, y, 100, 100);
        context.fillStyle = pattern;
        context.fill();
    };
    imageObj.src = src;
    context.restore();
}
                .save() and .restore() are a perfectly valid way to do this.  Your issue is a classic aync error in that your .restore() code is being called before your callback.  In otherwords, this is happening:
context.save()
context.restore();
function(){
    context.fillStyle = pattern;
}
put context.restore() inside your callback function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With