如何确定画布何时完成加载 [英] How to determine when a canvas has finished loading

查看:112
本文介绍了如何确定画布何时完成加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I was making a rather large canvas that was filled with 1x1 pixels, and I wanted to make a loading screen for it. The problem after the loop filling the canvas finishes, it alerts that it has finished loading, but the canvas has not actually changed. I made a jsfiddle here to demonstrate. How do I actually find out when the canvas has actually loaded using javascript or Jquery, and what is causing 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!');


推荐答案

因为你说jquery是确定,只是

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

Any code that needs the canvas fully loaded can go 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");
}

这篇关于如何确定画布何时完成加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆