javascript - 使用 vanilla javascript 随机移动 svg 对象
问题描述
我想使用香草 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" />
解决方案
您需要使用“香草”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 ......
推荐阅读
- docker - Pip install 实际上是在一个 docker 容器中(气流)
- javascript - Javascript 中使用对象引用的“闭包”:“私有变量”存储在哪里?
- mysql - 在 MySQL 中计算一个复杂的累积值
- postgresql - 带有“DISTINCT ON”的“CAST”函数不会改变字段的类型
- matplotlib - matplotlib 中的乳胶字体
- ruby - 无法从 nil 确定时区(ArgumentError)
- database - 复制源文件时管理 Excel 源工作簿中的链接
- java - 关于重新排序:尽管使用了 volatile,为什么这段代码会抛出 RuntimeException?
- php - 文件上传问题
- ios - IOS Swift TextView UITapGestureRecognizer 与标签移动光标