Need help with animation on JavaScript without jQuery - javascript

I have got a div object for example (Simple Image), and I need my picture to move to right and left and backward without any frame and border. My picture will collide with end (right side of my page) and move backward to left and then action with right side too. This will be only on JavaScript.
Edit:
<html>
<head>
<script>
function dvig () {
var xx = 50;
var corner_left=200 +'px';
var corner_right=100 +'px';
var move; var move2;
var dv=document.getElementById("adam");
if(dv.style.left<=corner_right) {
move=1;
move2=1;
}
if(dv.style.left>=corner_left) {
move2=0;
move=0;
}
if(move=1) {
dv.style.left=parseInt(document.getElementById("adam").style.left)+xx;
}
if (move2=0) {
move=0;
dv.style.left=parseInt(document.getElementById("adam").style.left)-xx;
}
}
function chustro() {
setInterval("dvig()", 100);
}
</script>
</head>
<body onload="chustro()">
<img id="adam" style="position: absolute; top: 100px; left: 100px; width: 40px; height: 40px; background-color: red">
</body>
</html>

Your going to have to setup a iterative process that runs every X milliseconds. Each time its run you have to update the div's position a bit and check if it hits a side and reverse direction.
function doWork{
// move current direction a little
// check if past the left edge and change directions
// check if past the right edge and change direction
}
setInterval(doWork, 10);
Update:
Based on your code, check this example:
http://jsfiddle.net/HT9A4/

Related

Moving a sprite image using arrow keys in JavaScript

I have to animate a robo such that it would move around an HTML5 Canvas.
Here's my image: https://i.stack.imgur.com/oecS2.png
The instructions I have to work on my animation are:
If you are not pressing a button, the skeleton should not move and should just be facing you.
If you press the right arrow key or “d” then it should move to the right.
If you press the left arrow key or “a” then it should move to the left.
If you press the up arrow key or “w” then it should move up.
If you press the down arrow key or “s” then it should move down
If it gets to the edge of the canvas, it should keep walking but not move
I haven't been able to find any helpful resources that would guide me to move my sprite image using arrow keys. And I know a bit of making an image move using mouse but not using arrow keys. But here's what I've tried so far.
JavaScript:
var tID;
function stopAnimate()
{
clearInterval(tID);
}
function animateScript()
{
var position = 256;
const diff = 256;
tID = setInterval ( () => {
document.getElementById("image").style.backgroundPosition = `-${position}px 0px`;
if (position < 1536)
{
position = position + diff;
}
else
{
position = 256;
}
}, 100);
}
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' type='text/css' href='Robot.css'>
</head>
<body>
<h2>Animation</h2>
<div id ="demo">
<p id="image" onmouseover="animateScript()" onmouseout="stopAnimate()"></p>
</div>
<script src="Animate.js"></script>
</body>
</html>
CSS:
body
{
background: white;
color: black;
}
#image
{
height: 256px;
width: 256px;
background: url('robo.png') 0px 0px;
}
The code above isn't the right thing that I need but I was just testing it using my knowledge about moving sprites using a mouse but I need some help on rotating my image using arrow keys. Any help would be appreciated!

Scroll to an ID minus some pixels

I have below code already and working well to scroll down to the ID ('expressRate') on page loading. But with change of requirement the page should scroll down to a point 50 pixels above the div ID 'expressRate'. Any help would be appreciated.
$location.hash('expressRate');
$anchorScroll();
try this javascript code after you scroll to the tag 'expressRate'
window.location('#expressRate');
window.scrollBy(0,-50);
//get the element
var $expressRate = $('#expressRate');
//get the vertical distance of the element from the top of the page
var verticalPositionOfElement = $expressRate.offset().top;
//added a timeout just so you could see the start and then the
//adjustment
setTimeout(function () {
//scroll the window down the element distance, minus whatever
$(window).scrollTop(verticalPositionOfElement - 50);
}, 1000);
html, body {
min-height: 5000px;
}
#expressRate {
min-height: 200px;
margin-top: 1000px;
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="expressRate">
window.scroll(0,findPos(document.getElementById("expressRate")) - 50);
function findPos(obj) {
var curtop = 0;
if (obj.offsetParent) {
do {
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return [curtop];
}
}
You don't need the framework for something so simple, you can use getBoundingClientRect() on the element you are trying to scroll to. Let's say:
The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport.
Let's say that: result = b.getBoundingClientRect();
It will give you element's box in DOM related things but you really wanna only one thing: result.x coordinate representing x coordinate in pixels keeping in mind the VIEWPORT.
Now you can simply use window.scrollTo() to that element's x coordinate -50px to scroll where you wanted.
HTML:
<button id="but" onClick="scrol()">SCROLL TO 50px before</button>
<div id="a"><span id="b">WHERE AM I?</span></div>
<div id="tall"> </div>
<pre></pre>
CSS:
#but { position: fixed; }
#a { padding:16px; position: absolute; top:300px;}
#b { background:yellow;}
#tall { height:2000px }
JS:
function scrol(){
var b = document.querySelector('#b');
window.scrollTo(b.x, b.y - 200)
}
Voila, a 2-liner vanilla solution :)
For a quick demo, Please look at this Fiddle: http://jsfiddle.net/58gzv79h/1/
NOTE: In Fiddle, the solution is a bit bigger to show you how unlike other things in result, the X does not change from the time document was loaded.

How to adjust a Greensock.js tween based on browser scroll y position rather than by the time?

How would I go about adjusting the time manually based on the scroll position? What might that look like? To basically 'scroll' the tween? So that the tween reacts to the scrolling mouse's Y position rather than just trigger and execute based on a preset time?
IMHO, here is what you'll need to do:
You will need TimelineMax for sequencing your animations. Place
your animations in TimelineMax as you like them to be.
You'll need to figure out the maximum scroll position your window can scroll up to, beforehand. (This can also be re-calculated on browser resize as well but I haven't taken this into account in my example below). You can figure out with the
help of this answer. Also read the comments on that answer.
Upon scroll, you'll need to convert the current scroll position of
your window object into percentage that is: var currentScrollProgress=window.scrollY/maxScroll; such that your currentScrollProgress should always be between 0 and 1.
TimelineMax has a progress() method which takes values ranging
from 0 and 1 where 0 being the initial state of the animations
and 1 being the final state. Feed this currentScrollProgress
into it and you're done.
OR, you can tween the timeline itself that is: TweenMax.to(timeline,scrollTweenDuration,{progress:currentScrollProgress,ease:ease});.
Code used in my example is as follows:
HTML:
<div> </div>
<div> </div>
...
CSS:
html, body { margin: 0; padding: 0; }
div { width: 100%; height: 60px; margin: 2px 0; }
div:nth-child(odd) { background: #cc0; }
div:nth-child(even) { background: #0cc; }
JavaScript:
/*global TweenMax, TimelineMax,Power2*/
var myDIVs=document.querySelectorAll('div'),numDIVs=myDIVs.length;
var timeline=new TimelineMax({paused:true}),duration=.4,ease=Power2.easeOut,staggerFactor=.1,scrollTweenDuration=.4;
var scrollTimeout=null,scrollTimeoutDelay=20,currentScrollProgress=0;
var maxScroll=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight)-window.innerHeight; //see [https://stackoverflow.com/a/17698713/3344111]
function init(){
initTimeline();
listenToScrollEvent();
onScroll();
}
function initTimeline(){
for(var i=0; i<numDIVs; i+=1){ timeline.fromTo(myDIVs[i],duration,{opacity:0},{opacity:1,ease:ease},i*staggerFactor); }
}
function listenToScrollEvent(){
(window.addEventListener)?window.addEventListener('scroll',debounceScroll,false):window.attachEvent('onscroll',debounceScroll);
}
function debounceScroll(){
clearTimeout(scrollTimeout);
scrollTimeout=setTimeout(onScroll,scrollTimeoutDelay);
}
function onScroll(){
currentScrollProgress=roundDecimal(window.scrollY/maxScroll,4);
//timeline.progress(currentScrollProgress); // either directly set the [progress] of the timeline which may produce a rather jumpy result
TweenMax.to(timeline,scrollTweenDuration,{progress:currentScrollProgress,ease:ease}); // or tween the [timeline] itself to produce a transition from one state to another i.e. it looks smooth
}
function roundDecimal(value,place){ return Math.round(value*Math.pow(10,place))/Math.pow(10,place); }
//
init();
Here is the resulting jsFiddle. Hope it helps.
T
While Tahir's answer is correct and sufficient, there's a lot of unnecessary code to show the example.
A more concise snippet is:
var max_scroll = document.body.offsetHeight - window.innerHeight;
win.addEventListener('scroll', function(){
var scroll_perc = parseFloat(Math.min(window.pageYOffset / max_scroll, 1).toFixed(2));
TweenMax.to(tl, 0, {
progress: scroll_perc
});
});
var tl = new TimelineMax({paused: true});
// the rest of your timeline....

Stuttering orbit animation when updating css through javascript over small interval

I'm trying to make some DOM element rotate smoothly around a fixed point. I'm writing this from scratch using jQuery and no matter what update speed I choose for the setInterval or how small I go with the amount of degrees the orbit advances on each loop, I get this janky staircase animation effect. I've tried using jquery's .animate instead of the .css hoping it would smooth things out but I cant seem to get it to work. Any help is appreciated.
In other words, it's not as smooth as rotating an image in HTML5 canvas. I want to make it smoother.
Here is a jsFiddle demonstrating the issue.
Notice how the animation is not quite smooth?
For reference, here is the code:
HTML
<div id="div"></div>
<div class="dot"></div>
<button class="stop">STOP</button>
<button class="start">START</button>
CSS
#div{
position:absolute;
height: 20px;
width: 20px;
background-color: #000;
}
.dot{
position:absolute;
width: 5px;
height: 5px;
background-color: #000;
}
button{
position:absolute;
}
.stop{
top:200px;
}
.start{
top:225px;
}
THE ALL IMPORTANT JAVASCRIPT
$(document).ready(function(){
$('#div').data('angle', 90);
var interval;
$('.stop').on('click', function(){
if(interval){
clearInterval(interval);
interval = undefined;
}
});
$('.start').on('click', function(){
if(!interval){
interval = setBoxInterval();
}
});
interval = setBoxInterval();
});
function drawOrbitingBox(degrees){
var centerX = 100,
centerY = 100,
div = $('#div'),
orbitRadius = 50;
//dot might not be perfectly centered
$('.dot').css({left:centerX, top:centerY});
//given degrees (in degrees, not radians), return the next x and y coords
function coords(degrees){
return {left:centerX + (orbitRadius * Math.cos((degrees*Math.PI)/180)),
top :centerY - (orbitRadius * Math.sin((degrees*Math.PI)/180))};
}
//increment the angle of the object and return new coords through coords()
function addDegrees(jqObj, degreeIncrement){
var newAngle = jqObj.data('angle') + degreeIncrement;
jqObj.data('angle', newAngle);
return coords(newAngle);
}
//change the left and top css property to simulate movement
// I've tried changing this to .animate() and using the difference
// between current and last position to no avail
div.css(addDegrees(div, degrees), 1);
}
function setBoxInterval(){
var interval = window.setInterval(function(){
drawOrbitingBox(-0.2); //This is the degree increment
}, 10); //This is the amount of time it takes to increment position by the degree increment
return interval;
}
I'd rather not resort to external libraries/plugins but I will if that's the accepted way of doing this kind of stuff. Thank you for your time.
That's because the value you set for top and left properties is rounded up. You should try using CSS Transforms.
Combining CSS Animations/Transitions and CSS Transforms you should also be able to get the animation without JavaScript.
Oh, I run into that myself!
There is actually nothing you can do, the stuttering you see is the pixel size. The pixel is the minimal step for css based animations, you can't do "half pixels" or "0.2 pixels". You will see that the same keeps happening with css3 animations.
The only solution is to speed up your animation, i'm afraid.
Also, cosndsider using rquestAnimationFrame instead of interval: https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame

jquery mouse move capture inaccuracy

I'm facing an strange problem.
I capture the mouse movements with:
var mmoves = [];
jQuery(document).mousemove(function(event) {
mmoves.push({x:event.pageX, y:event.pageY})
}
Then I attach a div to the page like:
$("body").append('<div id="mouseemul" style="padding:0; margin:0; color: red; background-color: blue; width: 1px; height: 1px;">*</div>');
and then try to playback the moves
It works ok on most pages but on some pages the playback starts ("*" initial position) some pixels to the right (x). The y is ok but the x is about 120px to the right. On other pages it is accurate. On the not accurate pages, when the mouse goes close the right scrollbar it goes beyond the right page border and produces a horizontal scrollbar.
I think this has to do with some css styling of the page being playback.
Does anybody has an idea what may be causing this ?
How could I get the actual offset (in case there is an offset for such pages) ?
Thanks a lot,
Hernan
--Edited--
It is obvious that the x displacement is due to the positioning of the main document. The first element gives a $.position() of 0,134 and if I SUBSTRACT that amount from the recorded data the playback is accurate. The problem is that this displacement does not happen in every page and I dont know how to figure out when the displacement occurs and when not (to correct it by substracting).
Recording
If you want to capture and replay mouse movement you can try "recording" from the document.
This would use the x and y chords from the window.
To do this you can use the document DOM element:
var m = [];
// Using the document instead of body might solve your issue
$( document ).mousemove(function( e ){
m.push({ x : e.pageX, y : e.pageY });
});
Replaying
HTML/CSS
Your HTML/CSS should be a div on the page set with position: fixed which should match your javascript chord samples as fixed is absolutely positioned to the window:
<style>
.replay {
/* Use position fixed to match window chords */
position: fixed;
top: 0;
left: 0;
/* These are just for show */
border-radius: 20px;
background: red;
width: 10px;
height: 10px;
}
</style>
<div class="replay"></div>
Javascript
To replay your captured chords you can use something like this:
var $replay = $('.replay'), // Get mouse simulator
i = 0, l = m.length,
pos, t;
// Recursive animation function
function anim(){
// Cache current position
pos = m[i];
// Move to next position
$replay.css({ top: pos.y, left: pos.x });
i++;
// Exit recursive loop
if ( i === l )
clearTimeout( t );
// Or keep going
else
t = setTimeout(anim, 100); // Timeout speed controls animation speed
}
// Start animation loop
anim();
Demo
Try it out on this demo.

Categories