Нужна помощь с анимацией
Написал код с анимацией, хотел чисто на js без css вообщем квадрат стоит по центру экрана потом двигается на верх до конца экрана, потом на права до конца, потом вниз до конца потом налево и вверх обратно на свое место. И проблема у меня такая получилась вверх и направо он у меня идет, а вот вниз не хочет, точнее начинает идти потом проскакивает часть экрана и все, на лево вообще стоит на месте. не знаю что делать помогите
let box=document.getElementById(`red`); let delay=10; //скорость let coords=box.getBoundingClientRect(); //координаты в начальной точке let windowWidth=document.documentElement.clientWidth;//размер экрана let windowHeight=document.documentElement.clientHeight;//размер экрана let count=0; // let countLeft=0; // let countBottom=0;// Счетчики let countRight=0; // function edge() { let coords2=box.getBoundingClientRect(); // отслеживаю координаты if(coords2.y!=0) //двигаюсь вверх пока координата х не станет 0 { setTimeout(edge,delay); box.style.bottom= count+'px'; count++; }else if(coords2.x!=windowWidth-box.offsetWidth) //на право { setTimeout(edge,delay); box.style.left= countLeft+'px'; countLeft++; } /* else if(coords2.y!=windowHeight-box.offsetHeight) //вниз не работает как надо { setTimeout(edge,delay); box.style.top = countBottom +'px'; countBottom++; } */ /* else if(coords2.x==coords.x) //на лево вообще не срабатывает { setTimeout(edge,delay); box.style.right= countRight+'px'; countRight++; } */ /*Это чисто проверки для себя не влияет на работу кода*/ console.log(coords2.x); console.log(coords2.y); console.log('*******'); } //edge(); console.log(windowWidth,windowHeight); console.log(coords.x,coords.y); |
|
|
Анимацию через requestAnimationFrame нужно делать
<!DOCTYPE html> <html> <head> <style> #red { position: absolute; width: 25px; height: 25px; background-color: red; } body { height: 100%; } </style> </head> <body> <div id="red"></div> <button id="start">Start</button> <script> let box= document.getElementById('red'); const boxrect = box.getBoundingClientRect(); const boxWidth = boxrect.width; const boxHeight = boxrect.height const windowWidth=innerWidth; const windowHeight=innerHeight; const x0 = (windowWidth - boxWidth)/2; const y0 = (windowHeight - boxHeight)/2 box.style.left = x0 + 'px'; box.style.top = y0 + 'px'; let direction = 'up'; const rightX = windowWidth - boxWidth; const bottomY = windowHeight - boxHeight; const speed = 100; // px/s let lastT; let curX = x0; let curY = y0; const move = (nowT) => { if (lastT === undefined) lastT = nowT; let stop = false; const dt = nowT - lastT; const d = speed * dt / 1000; lastT = nowT; switch (direction) { case 'up': if (curY <= y0) { curY = Math.max(curY - d, 0); if (curY == 0) direction = 'right'; } else { curY = Math.max(curY - d, y0); if (curY == y0) stop = true; } break; case 'right' : curX = Math.min(curX + d, rightX); if (curX == rightX) direction = 'down'; break; case 'down': curY = Math.min (curY + d, bottomY); if (curY == bottomY) direction = 'left'; break case 'left' : curX = Math.max(curX - d, x0); if (curX == x0) direction = 'up'; break; } box.style.top = curY + 'px'; box.style.left = curX + 'px'; if (!stop) requestAnimationFrame(move); else lastT = undefined; } const start = document.getElementById('start'); start.addEventListener ('click', () => requestAnimationFrame(move)) </script> </body> </html> |
voraa,
не подскажите почему у меня анимация работала не так как надо? ведь логически то все верно. мне нужно понять может там нюансы какие-то есть? |
MallSerg,
не подскажите почему у меня анимация работала не так как надо? ведь логически то все верно. мне нужно понять может там нюансы какие-то есть? |
рони,
не подскажите почему у меня анимация работала не так как надо? ведь логически то все верно. мне нужно понять может там нюансы какие-то есть? |
Im_Ilya,
не используйте ==при сравнении, точные числа в вычислении координат редкость! лучше >= , >, <, <=. и не плодите однотипные сообщения. |
рони,
т.е. поэтому он у меня перескакивает часть экрана? |
Цитата:
|
Часовой пояс GMT +3, время: 06:46. |