gpt4 book ai didi

javascript - 如何制作网球从水平表面弹起的动画

转载 作者:行者123 更新时间:2023-12-03 07:23:41 26 4
gpt4 key购买 nike

我有一张网球的图像:

enter image description here

有必要制作一个球下落并随后从固体表面弹起的动画。

我得到了这种动画,但它看起来不现实:

要启动动画,请单击图像:

<svg id="svg1" version="1.1" xmlns="http://www.w3.org/2000/svg" 
xmlns:xlink="http://www.w3.org/1999/xlink"
width="200" height="200" viewBox="0 0 200 200" preserveAspectRatio="xMinYMin meet" style="border:1px solid" >

<image xlink:href="/image/hXyA5.png" x="82" width="25px" height="25px" >
<animateTransform attributeName="transform" type="translate" dur="1s" begin="svg1.click" values="0,0;0,168;0" repeatCount="3" />
</image>
<polyline points="5,190 190,190" stroke="silver" stroke-width="4" />

</svg>

第一次弹跳必须小于球下落的高度,第二次弹跳小于第一次弹跳的高度,第三次弹跳小于第二次弹跳的高度。

你是如何实现这一目标的?解决方案可能在 SMIL SVG、CSS、JS 上

首选 SMIL SVG 解决方案。

最佳答案

最现实的方法是用 JS 模拟物理。

类似这样的事情:

let ballElem = document.getElementById("ball");

let GRAVITY = 40; // Acceleration due to gravity (pixels / sec /sec)
let FLOOR_Y = 200 - 25; // Y coord of floor. The 25 here is because ball.y is the top of the ball.
let BOUNCINESS = 0.8; // Velocity retained after a bounce
let LIMIT = 0.1; // Minimum velocity required to keep animation running
let ball = {};
let lastFrameTime = null;

ballElem.addEventListener("click", startAnim);


function startAnim()
{
ball = {x: 82, y: 0, dx: 0, dy: 0};
lastFrameTime = null;
requestAnimationFrame(animStep);
}


function animStep(timestamp)
{
if (lastFrameTime === null)
lastFrameTime = timestamp;
// Milliseconds elapsed since last step
const elapsed = timestamp - lastFrameTime;
lastFrameTime = timestamp;

ball.dy += GRAVITY * elapsed / 1000;
ball.y += ball.dy;
ball.x += ball.dx; // not really used in this example

if (ball.y > FLOOR_Y) {
// Step has taken us below the floor, so we need to rebound the ball.
ball.y -= (ball.y - FLOOR_Y);
ball.dy = -ball.dy * BOUNCINESS;
}

// Update the <image> element x and y
ballElem.x.baseVal.value = ball.x;
ballElem.y.baseVal.value = ball.y;

// Request another animation step
if (Math.abs(ball.y - FLOOR_Y) > LIMIT || // Not on ground
Math.abs(ball.dy) > LIMIT || // or still moving
Math.abs(ball.dx) > LIMIT) {
requestAnimationFrame(animStep);
}
}
<svg id="svg1" 
width="200" height="200" viewBox="0 0 200 200" preserveAspectRatio="xMinYMin meet" style="border:1px solid" >

<image id="ball" xlink:href="/image/hXyA5.png" x="82" width="25px" height="25px"/>

</svg>

关于javascript - 如何制作网球从水平表面弹起的动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64757447/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com