【问题标题】:Canvas not being drawn html5 (javascript, closures)没有绘制 html5 的画布(javascript,闭包)
【发布时间】:2012-03-20 22:30:21
【问题描述】:

如果我删除“alert(stepHor);”线,我的画布上不会画任何东西。但是如果我让警报(stepHor),一切都按预期进行。如果它有类似的 img.onload,我会理解,但在这里我没有。它与“关闭”有关吗?提前致谢。

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

    }
}

【问题讨论】:

  • 何时/如何调用这个函数? imax 变量来自哪里?
  • imax 和 jmax 是全局变量,我这样定义它们:var imax=Math.floor($(window).width()/wireWidth); var jmax=Math.floor($(window).height()/wireHeight); 其中一个“线”实际上是一个“像素”,我在全局变量中定义它的大小

标签: javascript html canvas closures


【解决方案1】:

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

body.onload 或其他地方调用函数。

阻止警报让浏览器有足够的时间来初始化,除非你是一个反应速度为 10 毫秒的机器人:-D

【讨论】:

  • 这也是我的第一个想法,警报正在创建延迟,以确保加载 dom。相反,该函数只应在加载 dom 后调用。
  • canvas 什么时候需要准备好 DOM? jsfiddle.net/niklasvh/9xxM8
  • 抱歉,我忘了在我的 html 页面中,当我的图像完成加载时调用函数 imageReader(this),在这个函数结束时,我调用实际函数 draw(图像数据)
  • 就是这样,我将 for 循环包装在 $(document).ready 中,并且有效。谢谢!
  • @Niklas 是的,你是对的。只有旧 IE 上的画布和图像才需要它。我提出了错误的建议,但还是猜到了答案:-D
猜你喜欢
  • 2014-10-16
  • 2014-11-11
  • 2012-04-27
  • 2015-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-20
  • 1970-01-01
相关资源
最近更新 更多