如何在Canvas上为drawImage()的多个实例制作动画?

时间:2019-01-06 10:43:51

标签: javascript animation canvas

我是第一次使用画布动画,在尝试一次为多个图像设置动画时遇到问题。

我能够在画布上绘制多个图像并将它们随机放置。我可以在画布上获得单个图像的动画,但是只能从数组中绘制最后一个图像。

我知道问题在于clearRect()从所述数组中清除所有先前绘制的图像,但无法弄清楚如何仅在每个动画帧中绘制完所有图像后才清除clearRect,我想知道是否有人处理过像这样的事情,如果他们能指出我正确的方向,即在绘制所有图像后如何只清除clearRect()?

function animate() {
        srequestAnimationFrame(animate);

        for(let i = 0; i < images.length; i++) {
            let y = images[i].y;
            let img = new Image();
            img.src = images[i].url;

            img.onload = function() {
                // This is clearing all images drawn before the last image
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(this, images[i].x, y, images[i].width, images[i].height);
            }

            images[i].y -= 1;

            if(images[i].y < (0 - images[i].height)) {
                images[i].y = window.innerHeight;
                images[i].x = (Math.random() * (canvas.width - 160));
            }
        }
    }

我想为页面上垂直的所有图像设置动画,并在到达屏幕顶部后将其重置为底部,我可以这样做,但仅适用于上述最后一个图像

1 个答案:

答案 0 :(得分:0)

animate()函数中,更新y的值后,您需要再次绘制每张图像。另外,您需要清除每一帧的画布(animate()功能),而不是在绘制每张图像之后,因为clearRect将删除先前在画布上绘制的所有内容。需要清除矩形的原因是必须删除在先前位置绘制的图像。

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let cw = (canvas.width = window.innerWidth);
cx = cw / 2;
let ch = (canvas.height = window.innerHeight),
    cy = ch / 2;

let images = [
  {
    url: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/puppy150x150.jpg",
    x: Math.random() * cw,
    y: Math.random() * ch,
    width: 50,
    height: 50
  },
  {
    url: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/puppy200x200.jpg",
    x: Math.random() * cw,
    y: Math.random() * ch,
    width: 40,
    height: 40
  },
  {
    url:
    "https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/puppyBeagle300.jpg",
    x: Math.random() * cw,
    y: Math.random() * ch,
    width: 60,
    height: 60
  }
];

for (let i = 0; i < images.length; i++) {
  let y = images[i].y;
  images[i].img = new Image();
  images[i].img.src = images[i].url;

  images[i].img.onload = function() {
    // This is clearing all images drawn before the last image
    //ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(this, images[i].x, y, images[i].width, images[i].height);
  };
}

function animate() {
  requestAnimationFrame(animate);
  // clear the canvas here!
  ctx.clearRect(0, 0, cw, ch);
  for (let i = 0; i < images.length; i++) {
  //update the y value
    images[i].y -= 1;
    if (images[i].y < -images[i].height) {
      images[i].y = window.innerHeight;
      images[i].x = Math.random() * (canvas.width - 160);
    }
    //draw again the image
    ctx.drawImage(
      images[i].img,
      images[i].x,
      images[i].y,
      images[i].width,
      images[i].height
    );
  }
}
animate();
<canvas id="canvas"></canvas>