繁体   English   中英

使用香草JavaScript移动随机SVG对象

[英]Moving randomly svg objects using vanilla javascript

我想使用香草javascript随机移动我的svg对象,我通过将值添加到cx 10px使它移动元素,但是它喜欢跳跃,还有其他方法可以平滑地移动它,关键帧不起作用。 并且在svg文件中使用了javascript,我需要达到具有像这些元素一样的弹跳球的效果像这样的效果: 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" />

您可以为元素或类设置动画:

circle, my-class {
  animation: move 2s infinite alternate;
}

@keyframes move {
  0% {
    transform: translateX(50px);
  }
  100% {
    transform: translateX(0px);
  }
}

您需要构建一个循环来使用“香草” javascript来做到这一点。

一个基本的方法是:

let fps = 60  // frames per second

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

window.setInterval(loop, 1000 / fps)

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

一些库对此有很大帮助。 浮现在脑海的是SVG.js,two.js,Velocity.js ...

暂无
暂无

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

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