简单的画布动画 [英] Simply canvas animation
问题描述
我有一个简单的画布动画:两个矩形在两个不同的方向移动。然而,我觉得这可以更简化。
I have a simple canvas animation: two rectangles move in two different directions. However, I feel this could be simplified more.
http://jsfiddle.net/tmyie / R5wx8 / 6 /
var canvas = document.getElementById('canvas'),
c = canvas.getContext('2d'),
x = 10,
y = 15,
a = 20,
b = 50;
function move() {
c.clearRect(0, 0, 500, 300);
c.fillRect(0, y, 5, 5),
c.fillRect(b, 5, 15, 15);
x++;
y++;
b++
if (y > canvas.height || x > canvas.width) {
y = 0;
x = 0;
}
}
setInterval(move, 100);
例如,如果我想创建另外三个形状,会发生什么?现在,我必须为每个坐标创建更多的变量:
For example, what happens if I wanted to create another three shapes? At the moment, I'd have to create more variables for each coordinate:
x++;
y++;
b++
有没有办法将每个矩形转换成自己的对象? p>
Is there a way I could turn each rectangle into its own object?
推荐答案
您可以将它们转换成对象,例如:
You can certainly turn them into objects, for example:
function Rect(x, y, w, h, dltX, dltY, color) {
var me = this;
this.x = x;
this.y = y;
this.width = w;
this.height = h;
this.deltaX = dltX || 0; /// and deltas can be optional
this.deltaY = dltY || 0;
this.color = color || '#000'; /// color is optional
this.update = function(ctx) {
me.x += me.deltaX;
me.y += me.deltaY;
ctx.fillStyle = me.color;
ctx.fillRect(me.x, me.y, me.width, me.height);
}
}
deltaX
和 deltaY
是您要为每个更新移动矩形的数量。如果将这些设置为例如1,则 x
和 y
将每次增加1, update()
被调用。
The deltaX
and deltaY
are how much you want to move the rectangle for each update. If you set these to for example 1 then x
and y
will be increased with 1 each time update()
is called.
使用deltas可以简单地通过逆转delta值来创建bounces 。 delta = -delta
)以及诸如加速度,变速速度之类的东西,你可以通过三角函数使它们在特定的角度移动。
Using deltas makes it easy to create bounces (see demo below) by simply reversing the delta value (ie. delta = -delta
) as well as things such as acceleration, variate speed, you can feed them through trigonometric functions to have the object move in a specific angle and so forth.
你可以使用固定值,如果你愿意,但你会发现deltas长期有利(参考注释:它实际上是一个非常经典的方法第一个Pong游戏:-))。
You can used fixed values if you desire but you will discover that deltas are beneficial in the long run (ref. comment: it's actually a very classic method used in for instance the first Pong games :-) ).
现在我们已经定义了对象,我们可以简单地创建它的实例并将它们存储在数组中:
Now that we have defined the object we can simply create instances of it and store them in an array:
var rects = [
new Rect(10, 10, 100, 100, 1, -2),
new Rect(100, 1, 50, 50, 2, 1, '#f00'),
...
]
b $ b
从这里,它只是一个迭代数组更新每个对象的问题:
From here it's simply a matter of iterating the array to update each object:
function move() {
ctx.clearRect(0, 0, width, height);
for(var i = 0, r; r = rects[i]; i++) {
/// check any conditions here
r.update(ctx);
}
requestAnimationFrame(move);
}
requestAnimationFrame(move); /// start loop
这篇关于简单的画布动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!