How to determine when the canvas finished loading

So, I was making a fairly large canvas filled with 1x1 pixels, and I wanted to create a loading screen for it. The problem after the cycle fills the canvas ends, he warns that he has finished loading, but the canvas has not actually changed. Here I demonstrated jsfiddle . How do I really know when the canvas really loaded using javascript or jQuery and what causes this behavior?

var ctx=document.getElementById('canvas').getContext('2d'); for(var x=1;x<600;x++){ for(var y=1;y<600;y++){ var color= '#' + Math.floor (Math.random() * 16777215).toString(16); ctx.fillStyle=color; ctx.fillRect(x,y,1,1); } } alert('done!'); 
+4
source share
2 answers

Since you said jquery is fine, just fire a special event when the loops complete.

Any code that should fully load the canvas can be in the event handler.

 // Listen for custom CanvasOnLoad event $(document).on( "CanvasOnLoad", canvasOnLoadHandler ); var ctx=document.getElementById('canvas').getContext('2d'); for(var x=1;x<600;x++){ for(var y=1;y<600;y++){ var color= '#' + Math.floor (Math.random() * 16777215).toString(16); ctx.fillStyle=color; ctx.fillRect(x,y,1,1); } // fire CanvasOnLoad when the looping is done if(x>=599){ $.event.trigger({ type: "CanvasOnLoad" }); } } console.log("...follows the for loops."); // handle CanvasOnLoad knowing your canvas has fully drawn function canvasOnLoadHandler(){ console.log("canvas is loaded"); } 
+4
source

This is similar to progressive animation. Updating / promoting this animation from an executable function usually does not work immediately (updating the screen when this function completes).

Your canvas code is (automatically) wrapped in the onload function: window.onload=function(){ /*your code here*/ }; .
The last line of this function is alert('done!'); , so naturally you will get a warning before updating the screen and you will see zero.

One solution is to first set and display the boot image, and then using setTimeOut (say setTimeOut ), it displays the canvas, ending this canvas function with another setTimeOut to delete the boot image again.

Note: as you probably know, your code will generate (many) hexadecimal colors like #3df5 and #5d8a6 , both of which are invalid colors! You also used 16777215, but Math.random () needs to be multiplied by 16777216. To fix this, you can try:
color='#'+((Math.random()+1)*16777216|0).toString(16).substr(1);
It reads well about random colors.

See this JSFiddle result for an example.

Hope this helps.

+2
source

Source: https://habr.com/ru/post/1479236/


All Articles