如何确定canvas何时完成加载

所以我制作了一个相当大的canvas,里面装满了1×1像素,我想为它制作一个加载画面。 循环填充canvas完成后的问题,它警告它已完成加载,但canvas实际上没有改变。 我在这里做了一个jsfiddle来演示。 我如何实际找出使用javascript或Jquery实际加载canvas的时间,以及导致此行为的原因是什么?

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!'); 

既然你说jquery没问题,只需在循环完成循环时触发一个自定义事件。

需要完全加载canvas的任何代码都可以放在事件处理程序中。

 // 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"); } 

它就像一个加载进度动画。 从正在运行的函数更新/推进该动画通常不会立即起作用(当该函数完成时屏幕更新)。

你的canvas代码(自动)包装在一个onload函数中: window.onload=function(){ /*your code here*/ };
该函数的最后一行是alert('done!'); ,所以很自然你会在屏幕更新之前获得警报框,你会看到noize。

一种解决方案是首先设置并显示一个加载图像,然后使用setTimeOut (比如说30ms)渲染canvas,用另一个setTimeOut结束该canvas函数以再次移除加载图像。

注意:您可能知道,您的代码将生成(很多)十六色,如#3df5#5d8a6 ,这两种颜色都不是有效颜色! 您也使用了16777215,但Math.random()需要乘以16777216.要解决此问题,您可能需要尝试:
color='#'+((Math.random()+1)*16777216|0).toString(16).substr(1);
这里有一些关于随机颜色的好读物。

以JSFiddle 结果为例。

希望这可以帮助。