javascript - 使用 vanilla javascript 随机 move svg 对象

标签 javascript svg move

我想使用 vanilla javascript 随机 move 我的 svg 对象, 我通过向 cx 添加 10px 的值来使其 move 元素,但它喜欢它在跳跃,是否有其他方法可以平滑地 move 它,关键帧不起作用。并且javascript在svg文件中使用,我需要用这些元素来实现像弹跳球这样的效果 效果是这样的: https://codepen.io/pintergabor/pen/DywHc

这应该用作背景图片。

<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 500 500">
<defs>
    <style>
        .cls-1 {
            fill: url(#linear-gradient);
        }

        .cls-2 {
            fill: url(#linear-gradient-2);
        }

        .cls-3 {
            fill: url(#linear-gradient-3);
        }
        #circle{
            animate: circle 4s infinite linear;
        }
        @keyframes circle{
            to{
                transform: translate(55rem, 15px);
            }
        }
    </style>


    <linearGradient id="linear-gradient" x1="61.83" y1="217.56" x2="61.83" y2="256.64" gradientUnits="userSpaceOnUse">
        <stop offset="0" stop-color="#9dcb3b" />
        <stop offset="1" stop-color="#aa2d23" />
    </linearGradient>
    <linearGradient id="linear-gradient-2" x1="316.43" y1="64.69" x2="316.43" y2="98.31" xlink:href="#linear-gradient" />
    <linearGradient id="linear-gradient-3" x1="321.31" y1="319.11" x2="321.31" y2="396.98" xlink:href="#linear-gradient" />
</defs>
<title>elements</title>
<circle id="circle" class="cls-1" cx="61.83" cy="237.1" r="19.54" />
<polygon id="triangle" class="cls-2" points="316.43 64.69 297.01 98.31 335.84 98.31 316.43 64.69" />
<path id="plus" class="cls-3" d="M323.9,397h-5.18V319.11h5.18Zm36.35-36.35v-5.17H282.37v5.17Z" />

最佳答案

您需要使用“vanilla”javascript 构建一个循环来执行此操作。

实现这一点的基本方法是:

let fps = 60  // frames per second

function loop(){
   console.log('in loop')
}

window.setInterval(loop, 1000 / fps)

然后在循环函数中根据需要 move svg 元素。

一些库对此有很大帮助。我想到的一些是 SVG.js、two.js、velocity.js...

关于javascript - 使用 vanilla javascript 随机 move svg 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56369306/

相关文章:

javascript - 使用 IE8 及以上版本支持的 JavaScript 下载文件

javascript - 使用 JavaScript 事件模拟悬停

javascript - 水平 d3 树 : how to have root starting at top left instead of middle y-axis?

ios - 仅在 XIB 中使用自动布局约束 move UILabel?

c++ - 如何返回不可 move (但可复制)的对象?

algorithm - 想要 : Theory for Copy, 在树中的节点中 move (例如拖放)

php - 随机排列图像数组

javascript - 使用 Javascript 在悬停和单击时切换 CSS 背景颜色

css - SVG 使用元素和 :hover style

javascript - SMIL 动画在动态加载的外部 SVG 上失败