日期:2014-05-16  浏览次数:20433 次

怎么让for循环里面执行一次就等待一段时间
JScript code

<canvas id="mycanvas1" width="270" height="270"></canvas>
<script type="text/javascript">
  var ctx = document.getElementById("mycanvas1").getContext('2d');
  var img = new Image();
  img.onload = function(){
    for(var i = 0; i < 4;i++){
        ctx.drawImage(img,0,270*i,270,270,0,0,270,270);
    }
  }
  img.src = 'themes/img/1.png';
</script>



这里是代码。。我想每一帧就修改i的值。就可以换图。但是for循环里面一下就循环到最后了 没有体现出来过程。我把
ctx.drawImage(img,0,270*i,270,270,0,0,270,270); 封装成一个函数。利用setInterval 去调用 还是不行。。
 求哪位帮我改下
素材我也贴上来


------解决方案--------------------
不用for循环,给你一个参考:
JScript code

<html>
<script>
window.onload = function(){
    
    var value = [1,2,3,4];
    var index = 0;
    
    var timer = setInterval(change, 1000);
    
    function change(){
        if (index >= value.length) {
            clearInterval(timer);
            return;
        }
        var div = document.getElementById("d");
        div.innerHTML = value[index].toString();
        index++;
    }
}
</script>
<body>
<div id="d"></div>
</body>
</html>

------解决方案--------------------
for(var i = 0; i < 4;i++){
ctx.drawImage(img,0,270*i,270,270,0,0,270,270);
}

var me = this;
for(var i = 0; i < 4;i++){
(function(i){
ctx.drawImage(me , 270*i );
})(i)
}
------解决方案--------------------
HTML code
<canvas id="mycanvas1" width="500" height="500"></canvas>
<script type="text/javascript">
  var ctx = document.getElementById("mycanvas1").getContext('2d');
  var img = new Image();
  var i=0,t;
  img.onload = function(){t=setInterval("theforever_csdn()",1000); };
  img.style.position="absolute";
  img.style.top="-1000px";
  document.body.appendChild(img).src = 'http://avatar.profile.csdn.net/A/9/7/2_theforever.jpg';
  function theforever_csdn(){
     ctx.clearRect(0, 0, 500, 500);
     ctx.drawImage(img,0,0,120,120,i*100,0,120,120);
     i++;if(i==3) clearInterval(t);
  }
</script>

------解决方案--------------------
for(var i = 0; i < 4;i++){
ctx.drawImage(img,0,270*i,270,270,0,0,270,270);
}


==》
drawImage(img,i);

function drawImage(img,index)
{
ctx.drawImage(img,0,270*index,270,270,0,0,270,270);
index++;
if(index < 4){
setTimeout(function(){drawImage(img,index);});
}
}