Google gravity and gravity script are two nice demonstrations. but no source code or tutorials are available. and the original JS files are very big. How can I create a Gravity effect with Drag & drop(specially being "Throw able" and "rotatable" like google gravity) on a certain element?
You will want to start with a physics engine, the one Google Gravity uses is Box2Djs which is a javascript port of Box2D. You can read the manual for Box2D to learn how to use it, though the manual itself states that you will have little idea what you are doing without some knowledge of rigid body physics (force, impulse, torque, etc), though these examples may help you get started.
If you want to write the physics engine yourself you will have to at least implement 2D rigid body dynamics and collision detection for it to look like the examples you gave. A tutorial for doing that would be called a computer simulation class and would have a linear algebra and physics I prerequisite, it's not a trivial task.
Afterwards, you will have to learn about javascript animation techniques. I recommend learning about window.requestAnimationFrame
. Using setInterval(stepFunction, time)
will work but it won't be as efficient as it could be in modern browsers.
Look a this jquery plugin on github JQuery.throwable
just do $("Selector").throwable()
and the object will be under gravity
One other framework to consider: Matter.js — Demo: Easy Physics Sandbox in JavaScript.
The Physics
Gravity is hard. That's because gravity is curved spacetime, and we can only make 2d representations of this warping that happens in the third dimension.
On the other hand -- moving an element at a consistent 9.8 m/s^2 in a linear direction towards one direction, that's actually not too hard to implement.
The CSS Solution
All we really need is transition: all 1s linear;
to control the speed of the animation, margin-top
to animate the element moving downward, and transition-timing-function
with a cubic-bezier
that's fairly representative of 9.8 m/s^2.
The Demo
document.addEventListener('DOMContentLoaded', function(event) {
document.getElementById('drop').addEventListener('click', function(ev) {
div = document.createElement('div');
div.classList.add('gravity-affected-object');
image = document.createElement('img');
image.src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Red_Apple.jpg/640px-Red_Apple.jpg';
image.width = 100;
image.classList.add('gravity-affected-object');
div.style.position = 'absolute';
div.style.left = '50%';
div.appendChild(image);
document.getElementById('page-top').appendChild(div);
setTimeout(function() {
div.style.marginTop = '1000px';
}, 100);
});
});
.gravity-affected-object {
transition: all 1s linear;
transition-timing-function: cubic-bezier(0.33333, 0, 0.66667, 0.33333);
z-index: -5000;
}
<div id="page-top"></div>
<button id="drop">Drop</button>
© 2022 - 2024 — McMap. All rights reserved.