SVG之获取路径长度,创建获取SVG元素(6)

SVG之获取路径长度,创建获取SVG元素(6)

说明:代码中,所有的namespace(命名空间)是固定的。需要记住,这是对SVG元素进行DOM操作所必需的

获取SVG元素

注意:是获取SVG元素哦!不是svg元素。意思就是获取所有SVG标签元素

  • document.getElementsByTagNameNS(namespace, ‘SVG标签名’)

上述方法用来获取SVG元素

<svg id="svg" width="500" height="500">
    <rect x="10" y="10" width="100" height="100"></rect>
</svg>
<script>
    var namespace = 'http://www.w3.org/2000/svg',
        svg = document.getElementsByTagNameNS(namespace
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的光点沿着 SVG 路径移动的示例: 首先,我们需要一个 SVG 路径,并在路径上添加一个“marker”元素,用于表示光点。代码如下: ```html <svg width="400" height="400"> <path id="motionPath" d="M 100 100 Q 200 50 300 100 Q 350 150 300 200 Q 200 250 100 200 Q 50 150 100 100" fill="none" stroke="#ccc" stroke-width="2" /> <marker id="point" viewBox="0 0 10 10" refX="5" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"> <circle cx="5" cy="5" r="2" fill="yellow" /> </marker> <circle id="movingPoint" cx="100" cy="100" r="5" fill="red" /> </svg> ``` 接下来,我们使用 JavaScript 来实现光点沿着路径移动的效果。具体实现如下: ```javascript // 获取路径元素和光点元素 const motionPath = document.querySelector('#motionPath'); const movingPoint = document.querySelector('#movingPoint'); // 获取路径的总长度 const pathLength = motionPath.getTotalLength(); // 设置光点元素的“marker-end”属性为我们定义的marker元素 movingPoint.setAttribute('marker-end', 'url(#point)'); // 定义动画函数 function animate() { // 获取当前时间 const currentTime = performance.now(); // 计算路径上的位置 const pointAtLength = motionPath.getPointAtLength(currentTime / 10 % pathLength); // 更新光点的位置 movingPoint.setAttribute('cx', pointAtLength.x); movingPoint.setAttribute('cy', pointAtLength.y); // 循环调用动画函数 requestAnimationFrame(animate); } // 开始动画 animate(); ``` 在上面的代码中,我们使用了 `performance.now()` 函数获取当前时间,并计算出路径上对应的位置。然后,我们更新了光点的位置,并使用 `requestAnimationFrame()` 循环调用动画函数。 现在,您可以在浏览器中运行这段代码,看到一个光点沿着 SVG 路径移动的效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值