簡體   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