如何确定画布何时完成加载

How to determine when a canvas has finished loading

本文关键字:加载 布何时 何确定      更新时间:2023-09-26

所以我制作了一个相当大的画布,填充了1x1像素,我想为它制作一个加载屏幕。问题是在循环填充画布完成后,它警告它已经完成加载,但画布实际上并没有改变。我在这里做了一个示范。我实际上如何发现当画布实际使用javascript或Jquery加载,是什么导致这种行为?

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是ok的,就在循环完成时触发一个自定义事件。

任何需要画布完全加载的代码都可以在事件处理程序中执行。

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

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

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

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

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

以JSFiddle结果为例。