所以我正在制作一个相当大的 Canvas ,其中填充了 1x1 像素,我想为它制作一个加载屏幕。循环填充 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");
}
关于javascript - 如何确定 Canvas 何时完成加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16384765/