1

I am trying to create div that 3D rotates on the X and Y axis so that it always faces the mouse cursor.

I am using vanilla Javascript and Velocity.js for the animation library.

Here is my Javascript code so far, please see the Codepen link for the html and css too:

var el = document.querySelector("#circle");// get mouse position on x y
onmousemove = function(event) {
var x = event.clientX
var y = event.clientY

var HEIGHT = document.body.clientHeight;
var WIDTH = document.body.clientWidth;

console.log("x position: "+ x +", " + "y position: " + y);


var calcX= Math.floor(x/10)
var calcY= Math.floor(y/10)

Velocity(el, {rotateX:calcX})
Velocity(el, {rotateY:calcY})

// rotate element towards x and y co-ordinates

};

http://codepen.io/anon/pen/bpzjar

I know that the math calculation isn't correct, if someone knows what the correct code for that, that would be awesome!

But I'm mainly trying to look at why the code is so slow and it seems to calculate and go to through each degree rather than going straight to what the final calculation would be so that its fast and responsive.

If someone could help me figure it out that would be great.

thanks!

Marco Angelo
  • 79
  • 1
  • 8

3 Answers3

0

By default, velocity.js has a duration of 400 milliseconds for transforms. Every time your mouse cursor changes position, rotateX will queue up a new ease to the new rotation.

Maybe this is closer to what you want:

Velocity(el, {rotateX:calcX, duration:10}, { queue: false })
Velocity(el, {rotateY:calcY, duration:10}, { queue: false })
Bemmu
  • 17,849
  • 16
  • 76
  • 93
0

You don't need velocity for what you want.

All you need is requestAnimationFrame (velocity uses it inside). Please read this post by Paul Irish, he explain how to use requestAnimationFrame better than me

And please see this working fiddle https://jsbin.com/vekuce.

Hope it help.

AldoRomo88
  • 2,056
  • 1
  • 17
  • 23
0

As a calculation approach you can map your mouse position to degree values:

var calcY = Math.round(map_range(x, 0, WIDTH,  -60, 60));
var calcX = Math.round(map_range(y, 0, HEIGHT, 60, -60));

function map_range(value, low1, high1, low2, high2) {
    return low2 + (high2 - low2) * (value - low1) / (high1 - low1);
}

Javascript has not native Math.map function but the simple helper included above will do it (credit to this SO answer)

This will rotate between from -60 to 60 degrees on both axis.

See the codePen example for this.

As others have already mentioned; Velocity.js is more for transitions (over time animations) and you don't need it for just follow mouse interactions.

Nevertheless you can use as well the .hook function helper from Velocity.js - which jumps directly to a value (this is what I've used in the codePen example).

Velocity.hook(el, "rotateX", calcX+"deg");
Velocity.hook(el, "rotateY", calcY+"deg");
Community
  • 1
  • 1
michaPau
  • 1,598
  • 18
  • 24