[英]How can I animate multiple instances of drawImage() on a 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));
}
}
}
我想为页面上垂直的所有图像制作动画,并在到达屏幕顶部后将其重置为底部,我可以进行此操作,但仅适用于上述最后一个图像
在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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.