【发布时间】:2018-09-04 00:10:27
【问题描述】:
我想在 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>
如果有人知道一种方法可以在仅编写几行代码的同时为多个对象设置动画,我们将不胜感激。提前致谢!
【问题讨论】:
-
听起来你应该使用游戏引擎,这里有几个:github.com/collections/javascript-game-engines
-
您根本不应该使用
class。您的目标不是创建一个对象(具有数据属性和方法),而只是绘制一个矩形。为此使用普通的function。
标签: javascript class ecmascript-6 html5-canvas