简体   繁体   English

如何在 Javascript 中单击随机运动 animation?

[英]how to do click random motion animation in Javascript?

I am trying to create an animation like an object have to move randomly and whenever someone clicks on the object(in this case it a div) the object should hit the edges of the browser and come back smoothly and again start moving randomly(hope you are getting my point) I have been surfing the internet from past few days to how to do this by means of any library or by custom coding but I didn't figure out the answer.我正在尝试创建一个 animation 就像 object 必须随机移动,每当有人点击对象(在这种情况下是一个 div)时,ZA8CFDE6331BD59EB2AC96F8911B59EB2AC96F8911B59EB2AC96F8911C4B666Z 应该会碰到浏览器的边缘并再次顺利返回明白了我的意思)过去几天我一直在网上冲浪,以了解如何通过任何库或自定义编码来做到这一点,但我没有找到答案。

I tried to do it on my own but didn't succeed.我尝试自己做,但没有成功。 Here is my code这是我的代码

 let test = document.querySelector(".test"); test.addEventListener("click",function(e){ let check = e.offsetX switch(true){ case(e.offsetX <= this.offsetWidth / 6): console.log("its above 50") gsap.to(".test",{x:window.innerWidth/2.7,y:50}) break; case(e.offsetX <= this.offsetWidth / 3): console.log("its above 100") break; case(e.offsetX <= this.offsetWidth / 2): console.log("its above 150") gsap.to(".test",{/* x:window.innerWidth/2.7 */y:50}) break; case(e.offsetX <= this.offsetWidth / 1.5): console.log("its above 200") break; case(e.offsetX <= this.offsetWidth / 1.2): console.log("its above 250") gsap.to(".test",{x:0-(window.innerWidth/2.7),y:50}) break; } console.log(e.clientX) })
 *{ box-sizing:border-box; } body { background-color: #fff; text-align: center; margin-top: 100px; }.bgcolor { background-color: black; color: rgba(255, 255, 255, 0.8); }.test{ width:300px; height:210px; margin:0 auto; display:flex; flex-wrap:wrap; }.check{ border:2px solid black; width:50px; height:105px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.6.1/gsap.min.js"></script> <div class="test test1" style="background:#FCD757;" > </div>

Using Math.random() method i created 2 values and adjusted them accordingly, inorder to make them more sensible ( not moving outside div element ).使用 Math.random() 方法,我创建了 2 个值并相应地调整了它们,以使它们更明智(不要移到 div 元素之外)。 After that i used setInterval method and stored it in global variable to set it again or clear it using clearInterval method.之后我使用 setInterval 方法并将其存储在全局变量中以再次设置它或使用 clearInterval 方法清除它。 Finally created moveAtSpecifiedPos function helps you to set the position when it is clicked最后创建 moveAtSpecifiedPos function 帮助您设置 position 时单击它

Change the attributes of the div with class ball to figure out animation speeds and smoothness !用 class 球改变 div 的属性,计算出 animation 的速度和平滑度! One thing I really was not able to figure out how to make collision at right time using js一件事我真的无法弄清楚如何使用 js 在正确的时间进行碰撞

 // getting ball and ball contained div const ball = document.querySelector('.ball'); const ball_div = document.querySelector('.moveObj'); let animation_time, transition_type, restart_time; animation_time = ball.getAttribute("data-animation-time"); transition_type = ball.getAttribute("data-transition-type"); restart_time = ball.getAttribute("data-resart-time"); ball.style.transition = `${animation_time} ${transition_type}`; // getting main div's height and width in which ball moves let max_movement_height = ball_div.scrollHeight; let max_movement_width = ball_div.scrollWidth; let ball_half_height = ball.scrollHeight / 2; let top_wall = (max_movement_height / 2 - ball_half_height); let bottom_wall = -1*(top_wall); let right_wall = (max_movement_width/2 - ball_half_height); let left_wall = -1*(right_wall); let intveral, num; wall__sides = { top: top_wall+"px", bottom: bottom_wall+"px", left: left_wall+"px", right: right_wall+"px" }; function start_animtion() { interval = setInterval(function () { num = Math.round(randomNumber(0, 100)); if (num.== num % 2) { move_X = Math,round(randomNumber(1? 2)) == 1. wall__sides:left. wall__sides;right. } else { move_X = randomNumber(parseInt(wall__sides,left). parseInt(wall__sides;right)) + "px". } if (num === num % 2) { move_Y = Math,round(randomNumber(1? 2)) == 1. wall__sides:top. wall__sides;bottom. } else { move_Y = randomNumber(parseInt(wall__sides,bottom). parseInt(wall__sides;top)) + "px". } ball.style,transform = `translate(${ move_X}; ${move_Y})`, }; parseInt(animation_time)); } function finish_animation() { clearInterval(interval); moveAtSpecifiedPos(). setTimeout(function() { ball;innerText = "catch me "; start_animtion(), }; parseInt(restart_time)), } function randomNumber(min. max) { return Math;random() * (max - min) + min. } function moveAtSpecifiedPos() { ball;innerText = "caught". ball.style,transform = "translate(0; 0)"; } start_animtion();
 *{ box-sizing: border-box; } body { margin: 0 }.moveObj { background: black; height: 100vh; position: relative; width: 100%; overflow: hidden; }.ball { --width: 100px; --height: 100px; width: var(--width); height: var(--height); width: px; background: white; top: calc(50% - var(--height) / 2 ); left: calc(50% - var(--width) / 2); border-radius: 50%; position: absolute; cursor: pointer; display: flex; align-items: center; justify-content: center; }
 <div class="moveObj"> <div class="ball" onclick="finish_animation()" data-resart-time="2000ms" data-transition-type="ease" data-animation-time="400ms"> Catch me </div> </div>

Simple bounce of the walls and changing direction when clicked:单击时墙壁的简单反弹和改变方向:

 document.addEventListener("DOMContentLoaded", e => { const test = document.getElementById("test"), rect = test.getBoundingClientRect(), rectBox = test.parentNode.getBoundingClientRect(), xMax = rectBox.width + rectBox.x - rect.width, yMax = rectBox.height + rectBox.y - rect.height, maxSpeed = 1; let x = rect.x, y = rect.y, xDelta, yDelta; setSpeed(); test.addEventListener("click", setSpeed); window.requestAnimationFrame(move); test.classList.toggle("move", true); function move(timestamp) { x = x + xDelta; y = y + yDelta; if (x < rectBox.x || x > xMax) { xDelta = -xDelta; x = x < rectBox.x? rectBox.x: xMax; } if (y < rectBox.y || y > yMax) { yDelta = -yDelta; y = y < rectBox.y? rectBox.y: yMax; } test.style.left = x + "px"; test.style.top = y + "px"; window.requestAnimationFrame(move); }; function setSpeed() { xDelta = rand(-maxSpeed, maxSpeed); yDelta = rand(-maxSpeed, maxSpeed); } function rand(min, max) { return Math.random() * (max - min + 1) + min; } });
 html, body { height: 100%; margin: 0; padding: 0; user-select: none; }.box { width: 100%; height: 100%; } *{ box-sizing:border-box; } body { background-color: #fff; text-align: center; }.bgcolor { background-color: black; color: rgba(255, 255, 255, 0.8); }.test { width:100px; height:100px; margin:0 auto; display:flex; flex-wrap:wrap; background-color: #FCD757; }.test.move { margin: 0; position: absolute; }.check{ border:2px solid black; width:50px; height:105px; }
 <div class="box"> <div id="test" class="test"></div> </div>

Pass event on click into a function, then set you collision variables and check them in conditionals.将点击事件传递给 function,然后设置碰撞变量并在条件中检查它们。 You can use CSS variables for the animations and set them using javascript with the document.documentElement.您可以将 CSS 变量用于动画,并使用 javascript 和 document.documentElement 设置它们。

 let test = document.querySelector(".test") function moveBox(e){ const root = document.documentElement; const winTop = document.documentElement.getBoundingClientRect().top const winBot = document.documentElement.getBoundingClientRect().bottom const winLeft = document.documentElement.getBoundingClientRect().left const winRight = document.documentElement.getBoundingClientRect().right let xpos = e.offsetX let ypos = e.offsetY const box = e.target.getBoundingClientRect() const widthCenter = box.width - (box.width / 2) const heightCenter = box.height - (box.height / 2) const disFromTop = window.pageYOffset + e.target.getBoundingClientRect().top const disFromBot = window.pageYOffset + e.target.getBoundingClientRect().bottom - box.height const disFromLeft = window.pageXOffset + e.target.getBoundingClientRect().left const disFromRight = window.pageXOffset + e.target.getBoundingClientRect().right - box.width // should equal the animations duration as set in CSS const duration = 500; let left = false, right = false, up = false, down = false; xpos < widthCenter? left = true: right = true ypos < heightCenter? up = true: down = true const classNames = ['animateLeft', 'animateRight', 'animateUp', 'animateDown'] const rootClass = ['left', 'right', 'top', 'bottom'] if (left === true && xpos < ypos && xpos < e.target.clientHeight - ypos) { root.style.setProperty(`--${rootClass[0]}Anim`, `${winLeft}px`) root.style.setProperty(`--${rootClass[0]}`, `${disFromLeft}px`) e.target.classList.add(classNames[0]) setTimeout(() => { e.target.classList.remove(classNames[0]) root.style.removeProperty(`--${rootClass[0]}Anim`) root.style.removeProperty(`--${rootClass[0]}`) }, duration) } if (right === true && e.target.clientWidth - xpos < ypos && e.target.clientWidth - xpos < e.target.clientHeight - ypos) { root.style.setProperty(`--${rootClass[1]}Anim`, `${winRight}px`) root.style.setProperty(`--${rootClass[1]}`, `${disFromRight}px`) e.target.classList.add(classNames[1]) setTimeout(() => { e.target.classList.remove(classNames[1]) root.style.removeProperty(`--${rootClass[1]}Anim`) root.style.removeProperty(`--${rootClass[1]}`) }, duration) } if (up === true && xpos > ypos && ypos < e.target.clientWidth - xpos) { root.style.setProperty(`--${rootClass[2]}Anim`, `${winTop}px`) root.style.setProperty(`--${rootClass[2]}`, `${disFromTop}px`) e.target.classList.add(classNames[2]) setTimeout(() => { e.target.classList.remove(classNames[2]) root.style.removeProperty(`--${rootClass[2]}Anim`) root.style.removeProperty(`--${rootClass[2]}`) }, duration) } if (down === true && xpos > e.target.clientHeight - ypos && e.target.clientHeight - ypos < e.target.clientWidth - xpos) { root.style.setProperty(`--${rootClass[3]}Anim`, `${root.clientHeight - box.height}px`) root.style.setProperty(`--${rootClass[3]}`, `${disFromBot}px`) e.target.classList.add(classNames[3]) setTimeout(() => { e.target.classList.remove(classNames[3]) root.style.removeProperty(`--${rootClass[3]}Anim`) root.style.removeProperty(`--${rootClass[3]}`) }, duration) } } test.addEventListener("click", moveBox)
 * { box-sizing: border-box; } /* added */:root { --width: 100px; --height: 100px; --leftAnim: 0; --rightAnim: 0; --topAnim: 0; --bottomAnim: 0; --left: calc(50% - 50px); --right: calc(50% - 50px); --top: calc(50% - 50px); --bottom: calc(50% - 50px); } body { background-color: #fff; text-align: center; margin-top: 100px; }.bgcolor { background-color: black; color: rgba(255, 255, 255, 0.8); }.test { position: absolute; top: var(--top); left: var(--left); width: var(--width); height: var(--height); display: flex; flex-direction: row; justify-content: center; align-items: center; background-color: red; border-radius: 50%; border: 1px solid black; }.check { border: 2px solid black; width: 50px; height: 105px; } /* added */.animateLeft { animation: moveLeft.5s ease-in-out; } /* added */.animateRight { animation: moveRight.5s ease-in-out; } /* added */.animateUp { animation: moveUp.5s ease-in-out; } /* added */.animateDown { animation: moveDown.5s ease-in-out; } /* added */ @keyframes moveLeft { 0% { left: var(--left); } 70% { left: var(--leftAnim); } 100% { left: var(--left) } } /* added */ @keyframes moveRight { 0% { left: var(--right); } 70% { left: calc(var(--rightAnim) - var(--width)); } 100% { left: var(--right); } } /* added */ @keyframes moveUp { 0% { top: var(--top); } 70% { top: var(--topAnim); } 100% { top: var(--top) } } /* added */ @keyframes moveDown { 0% { top: var(--bottom); } 70% { top: var(--bottomAnim); } 100% { top: var(--bottom) } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.6.1/gsap.min.js"></script> <div class="test test1" style="background:#FCD757;"> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM