If I remove the “alert(stepHor);” line, nothing is going to be drawn on my canvas. But if I let the alert(stepHor), everything goes perfectly as expected. If it had an img.onload of something like that, I would understand, but here I don’t. Does it have something to do with “closures”? Thanks in advance.
function draw(imageData) {
var canvas=document.getElementById('bg');
if(canvas.getContext){
var ctx=canvas.getContext('2d');
ctx.scale(0.4,0.4);
var stepHor=Math.floor(imageData.width/imax);
var stepVer=Math.floor(imageData.height/jmax);
alert(stepHor);
for(i=0;i<=imax;i++){
for(j=0;j<=jmax;j++){
var index=(j*stepVer+Math.floor((imageData.height-jmax*stepVer)/2))*(4*imageData.width)+(i*stepHor*4)+Math.floor((imageData.width-imax*stepHor)/2)*4;//the first 'Math.floor' member is to center the image vertically, the second 'Math.floor' member is to center the image horizontally
var red=imageData.data[index];
var green=imageData.data[index+1];
var blue=imageData.data[index+2];
var alpha=imageData.data[index+3];
ctx.fillStyle='rgb(' +red+ ',' +green+ ',' +blue+ ')';
ctx.fillRect(wireWidth*i,wireHeight*j,wireWidth,wireHeight);
}
}
}
}
Before drawing on canvas you need to wait before initialization of the page.
Call function in
body.onloador somewhat.Blocking alert gives browser enough time to init unless you’re a robot with 10ms reaction speed 😀