如何使用类和函数在 html5-canvas 上对多个对象进行动画处理?



我想在HTML5画布上为向下移动的多个矩形制作动画。有一个类,通过它,我可以通过简单地将参数传递给类来轻松创建我想要的任何矩形。问题出在类和内置方法"requestAnimationFrame"上,我只能对单个对象进行动画处理: 这是代码:

function resize(canvasElement) {
window.addEventListener("resize", function () {
canvasElement.width = window.innerWidth / 3;
canvasElement.height = window.innerHeight * 0.9975;
})
}
var radius = 5;
class roundRect {
constructor(rectX, rectY, rectHeight, rectWidth, stroke, fill, c) {
c.clearRect(rectX-100, rectY-100, rectX + 100, rectY + 100);
c.beginPath();
c.strokeStyle = stroke;
c.fillStyle = fill;
c.moveTo(rectX + rectWidth/2, rectY);
c.arcTo(rectX + rectWidth, rectY, rectX + rectWidth, rectY + rectHeight, radius);
c.arcTo(rectX + rectWidth, rectY + rectHeight, rectX, rectY + rectHeight, radius);
c.arcTo(rectX, rectY + rectHeight, rectX, rectY, radius);
c.arcTo(rectX, rectY, rectX + rectWidth / 2, rectY, radius);
c.closePath();
c.fill();
c.stroke();
}
}
var rectY = 10;
function animate() {
new roundRect(10, rectY, 50, 7, "red", "red", ctx);
requestAnimationFrame(animate);
rectY++;
}
{
var canvas = document.body.querySelector("#canvasOne");
canvas.width = window.innerWidth / 3;
canvas.height = window.innerHeight * 0.9975;
resize(canvas);
var ctx = canvas.getContext("2d");
animate();
}
canvasOne {
border:1px solid black;
}
<!DOCTYPE html>
<html>
<head>
<link href="homeComing.css" rel="stylesheet" />
<meta charset="utf-8" />
<title></title>
</head>
<body>
<canvas id="canvasOne"></canvas>
<script src="homeComing.js"></script>
</body>
</html>

如果有人知道一种在只编写几行代码时对多个对象进行动画处理的方法,将不胜感激。提前感谢!

在你的类中,你使用clearRect的方式可能会删除其他对象。
只需在外面做清晰的操作,然后您就可以获得多个矩形即可。

这是一个非常简单的例子:

class roundRect {
constructor(rectX, rectY, rectHeight, rectWidth, stroke, fill, c) {
var radius = 5;
c.beginPath();
c.strokeStyle = stroke;
c.fillStyle = fill;
c.moveTo(rectX + rectWidth / 2, rectY);
c.arcTo(rectX + rectWidth, rectY, rectX + rectWidth, rectY + rectHeight, radius);
c.arcTo(rectX + rectWidth, rectY + rectHeight, rectX, rectY + rectHeight, radius);
c.arcTo(rectX, rectY + rectHeight, rectX, rectY, radius);
c.arcTo(rectX, rectY, rectX + rectWidth / 2, rectY, radius);
c.closePath();
c.fill();
c.stroke();
}
}
var objects = [
{x:10, y:10, speed:{x:0, y:1},    w:50, h:7,  stroke:"red",   fill:"red"},
{x:50, y:10, speed:{x:0.5, y:1},  w:25, h:20, stroke:"black", fill:"blue"},
{x:190, y:10, speed:{x:-0.2, y:1}, w:20, h:18, stroke:"black", fill:"lime"}
]
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (i = 0; i < objects.length; i++) { 
var o = objects[i]
new roundRect(o.x, o.y, o.w, o.h, o.stroke, o.fill, ctx);
o.x += o.speed.x
o.y += o.speed.y    
}
requestAnimationFrame(animate);  
}
var canvas = document.body.querySelector("#canvasOne");
canvas.width = window.innerWidth / 3;
canvas.height = window.innerHeight * 0.9975;
var ctx = canvas.getContext("2d");
animate();
<canvas id="canvasOne"></canvas>

这是基于您的代码的示例,但是如果您真的想用更少的代码行完成所有这些工作,您应该使用游戏引擎。

最新更新