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:put
context.restore()inside your callback function.