HTML5 canvas "reset" fillStyle

I am starting to learn working with a canvas of JavaScript and HTML5.

I am trying to draw multiple elements with different patterns, but I always get the last installed pattern. I tried to use the save() and restore() methods to store stack statistics, but of course I'm doing something wrong, can someone 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(); } 
+7
source share
2 answers

.save() and .restore() are the perfect way to do this. Your problem - the classic aync error is that your .restore() code is called before your callback. In other words, this happens:

 context.save() context.restore(); function(){ context.fillStyle = pattern; } 

put context.restore() inside your callback function.

+10
source

A simple method inside the body does not call the draw function, because window.onload already calls this. Change window.onload to a function and call it from the body and her!

Example:

 var joda = 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"); }; <body onload="joda();"> 
-one
source

All Articles