在定时器/延迟的画布上移动不同的图像

Move different images across a canvas on a timer/delay

本文关键字:移动 图像 定时器 延迟      更新时间:2023-09-26

我希望能够在画布上移动一些图像,比如 5/6。图像的位置每次都会明显变化,模拟基本动画。图像将处于计时器/延迟状态,以便它们每秒左右移动一次。是否有我可以创建的函数,这样我就不必为图像一遍又一遍地重复相同的代码。如果图像是预加载的,那也很好,但我不确定一旦预加载图像如何操作图像。

如果还有一种方法可以使用requestAnimationFrame而不是setTimeout,那就更好了。

这是我当前的代码:

 window.addEventListener("load", eventWindowLoaded, false);
        function eventWindowLoaded () {
        images = new Array();
        images[0] = "images/1.png";
        images[1] = "images/2.png";
        images[2] = "images/3.png";
        images[3] = "images/4.png";
        images[4] = "images/5.png";
        imageObjs = [];
        for(var i = 0; i <= 4; i++){
            var imageObj = new Image();
            imageObj.src = images[i];
            imageObjs.push(imageObj);
        }       
drawFrame();
}
function drawFrame () { 

        setTimeout(function() {
        image = new Image();
        image.onload = function() {
            ctx.drawImage(imageObjs[0], 0, 0);
        }
        image.src = "images/1.png";
        }, 200);

        setTimeout(function () {
        image2 = new Image();
        image2.onload = function() {
            ctx.drawImage(imageObjs[1], 200, 0);
        };
        image2.src = "images/2.png";
    }, 1000);
}

你表示有兴趣让代码执行以下操作:

  • 预加载所有图像。
  • 在画布上移动图像。
  • 使用动画循环函数,以便代码不重复。
  • 使用 requestAnimationFrame 而不是 setTimeout 以提高效率。

下面是示例代码和演示:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var images=[];
images.push({x:20,y:200,moveX:5,maxX:250,delay:100,nextTime:0,url:'https://dl.dropboxusercontent.com/u/139992952/multple/cars1.png'});
images.push({x:20,y:30,moveX:10,maxX:100,delay:500,nextTime:0,url:'https://dl.dropboxusercontent.com/u/139992952/multple/sun.png'});
var imageCount=images.length;
for(var n=0;n<images.length;n++){ 
  var i=images[n];
  i.img=new Image();
  i.img.onload=start;
  i.img.src=i.url;
}
function start(){
  if(--imageCount>0){return;}
  requestAnimationFrame(animate);
}
function animate(time){
  requestAnimationFrame(animate);   
  var needsRedrawing=false;
  for(var n=0;n<images.length;n++){
    var i=images[n];
    if(time>i.nextTime){
      if(i.x+i.moveX<i.maxX){
        i.x+=i.moveX;
        i.nextTime+=i.delay;
        needsRedrawing=true;
      }
    }
  }
  if(needsRedrawing){
    ctx.clearRect(0,0,cw,ch);
    for(var n=0;n<images.length;n++){
      var i=images[n];
      ctx.drawImage(i.img,i.x,i.y);
    }
  }
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>