Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 canvas "reset" fillStyle

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();
}
like image 951
canvioso Avatar asked Nov 20 '11 20:11

canvioso


1 Answers

.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.

like image 194
Nobody Avatar answered Sep 25 '22 18:09

Nobody