I'm creating an application based on Vue.js. This application should contain some elements that are animated according to the mouse.
I created the animations in javascript and you notice that the elements are "tremendous" on the screen, you can see in the following video: link
All elements have absolute position and are animated by changing their position on the screen. Here is the code:
loadMouseMove: function () {
this.resetarPosicoes();
this.elementosMousemove = [];
var elementos = document.getElementsByClassName('efeitomouse');
for (var i = 0; i < elementos.length; i++) {
var config = JSON.parse(elementos[i].getAttribute('mmconfig'));
this.elementosMousemove.push({
objeto: elementos[i],
posicaoOriginal: {
top: elementos[i].offsetTop,
left: elementos[i].offsetLeft
},
fator: {
x: config.fx,
y: config.fy
}
});
}
this.mousemoveHabilitado = (elementos.length > 0);
this.mousePosicaoAtual = {
x: (this.tamanhoTela.width / 2),
y: (this.tamanhoTela.height / 2)
}
this.mouseUltimaPosicao = {
x: this.mousePosicaoAtual.x,
y: this.mousePosicaoAtual.y
}
},
resetarPosicoes: function () {
for (var i = 0; i < this.elementosMousemove.length; i++) {
this.elementosMousemove[i].objeto.style.left = '';
this.elementosMousemove[i].objeto.style.top = '';
}
},
mousemove: function (event) {
app.mouseUltimaPosicao.x = event.x;
app.mouseUltimaPosicao.y = event.y;
if (app.mousemoveHabilitado) {
cancelAnimationFrame(app.animationFrame);
app.animationFrame = requestAnimationFrame(app.animarMouseMove);
}
},
animarMouseMove: function () {
var deltaX = app.mouseUltimaPosicao.x - app.mousePosicaoAtual.x;
var deltaY = app.mouseUltimaPosicao.y - app.mousePosicaoAtual.y;
var deslocamentoMax = 20;
if (deltaX > 0) {
app.mousePosicaoAtual.x += (deltaX > deslocamentoMax) ? deslocamentoMax : deltaX;
} else {
app.mousePosicaoAtual.x += (deltaX < -deslocamentoMax) ? -deslocamentoMax : deltaX;
}
if (deltaY > 0) {
app.mousePosicaoAtual.y += (deltaY > deslocamentoMax) ? deslocamentoMax : deltaY;
} else {
app.mousePosicaoAtual.y += (deltaY < -deslocamentoMax) ? -deslocamentoMax : deltaY;
}
app.moverElementosMousemove(app.mousePosicaoAtual.x, app.mousePosicaoAtual.y);
if (Math.abs(deltaX) > 10 || Math.abs(deltaY) > 10) {
app.animationFrame = requestAnimationFrame(app.animarMouseMove);
}
},
moverElementosMousemove(x, y) {
var left = x - (app.tamanhoTela.width / 2);
var top = y - (app.tamanhoTela.height / 2);
for (var i = 0; i < app.elementosMousemove.length; i++) {
var elemento = app.elementosMousemove[i];
var px = elemento.posicaoOriginal.left + left * elemento.fator.x;
var py = elemento.posicaoOriginal.top + top * elemento.fator.y;
elemento.objeto.style.left = px + 'px';
elemento.objeto.style.top = py + 'px';
}
}
Is there any way to smooth this movement so that this effect does not occur any more?