尝试创建一个可以动态振荡对象属性的函数。我已经设法在函数之外创建它,但我无法让它在函数中工作。这是因为 Angular 变量,每帧都会增加。下面是一个使对象在 x 和 y 支柱上绕圈振荡的示例。
初始化...
var obj = new Ball(arguments...),
target = {
x: 100,
y: 100
},
angle = 0,
radius = 50,
speed = 0.1;
循环...
// clear canvas
obj.x = target.x + Math.cos(angle) * radius;
obj.y = target.y + Math.sin(angle) * radius;
angle += speed;
// rAF
这工作得很好,但是当我尝试使其可重用并将其变成一个函数时,它不起作用。
function oscillate(obj, target, angle, radius, speed) {
obj.x = target.x + Math.cos(angle) * radius;
obj.y = target.y + Math.sin(angle) * radius;
angle += speed;
}
如何让它在函数中工作?
最佳答案
这是因为 angle
不是通过引用传递的。 JS 没有引用传递。
您可以通过不声明本地变量来修改外部变量:
var map = document.getElementById('map'),
fx = map.getContext('2d');
var ball = {
x: 50,
y: 50,
radius: 50
},
target = {
x: map.width / 2,
y: map.height / 2,
},
angle = 0,
radius = 50,
speed = 0.1;
ball.draw = function(fx) {
fx.beginPath();
fx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
fx.fill();
};
function oscillate(obj, target, radius, speed) {
obj.x = target.x + Math.cos(angle) * radius;
obj.y = target.y + Math.sin(angle) * radius;
angle += speed;
}
(function update() {
fx.clearRect(0, 0, map.width, map.height);
oscillate(ball, target, radius, speed)
ball.draw(fx);
requestAnimationFrame(update);
}());
<canvas id='map'></canvas>
或者,传递一个对象:
var map = document.getElementById('map'),
fx = map.getContext('2d');
var ball = {
x: 50,
y: 50,
radius: 50
},
data = {
obj: ball,
target: {
x: map.width / 2,
y: map.height / 2,
},
angle: 0,
radius: 50,
speed: 0.1
};
ball.draw = function(fx) {
fx.beginPath();
fx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
fx.fill();
};
function oscillate(data) {
data.obj.x = data.target.x + Math.cos(data.angle) * data.radius;
data.obj.y = data.target.y + Math.sin(data.angle) * data.radius;
data.angle += data.speed;
}
(function update() {
fx.clearRect(0, 0, map.width, map.height);
oscillate(data)
ball.draw(fx);
requestAnimationFrame(update);
}());
<canvas id='map'></canvas>
关于javascript - 振荡功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35530021/