2012-03-02 242 views
0

如果我删除“alert(stepHor);”线,我的画布上没有任何东西可以画出来。但是,如果我让警报(stepHor),一切都如预期完美。如果它有像​​这样的img.onload,我会理解,但在这里我没有。它与“关闭”有什么关系?提前致谢。画布未被绘制html5(javascript,关闭)

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

    } 
} 
+0

当/怎么叫这个存在的功能? “imax”变量来自哪里? – ManseUK 2012-03-02 12:06:43

+0

imax和jmax是全局变量,我用这种方式定义它们:'var imax = Math.floor($(window).width()/ wireWidth); var jmax = Math.floor($(window).height()/ wireHeight);'其中'wire'实际上是一个'像素',其大小由全局变量定义 – user1011444 2012-03-02 14:34:21

回答

2

在绘制画布之前,您需要等待页面初始化之前。

呼叫功能body.onload或稍微。

拦截警报浏览器提供了足够的时间来初始化,除非你与10ms的反应速度的机器人:-D

+0

这也是我的第一个想法,警报正在创建延迟,确保dom被加载。相反,函数只能在加载dom之后调用。 – Evert 2012-03-02 12:12:35

+0

从什么时候'canvas'需要DOM准备好? http://jsfiddle.net/niklasvh/9xxM8/ – Niklas 2012-03-02 12:15:21

+0

哎呀对不起,我忘了在我的HTML页面中提到,函数imageReader(this)在我的图像加载完成后调用,并且在此函数结束时实际功能绘制(imageData) – user1011444 2012-03-02 14:28:04