写一个图片沿着svg 路径运动的示例
时间: 2023-06-28 11:04:51 浏览: 47
以下是一个简单的示例,展示了如何使用SVG路径和JavaScript使图像沿着路径运动。请注意,此示例仅涉及基本的SVG和JavaScript概念,具体实现可能会因应用场景而有所不同。
HTML代码:
```html
<svg width="500" height="500">
<path id="motionPath" d="M 100 250 C 200 50, 350 50, 450 250 S 700 450, 800 250" stroke="black" fill="transparent"/>
<image id="myImage" xlink:href="https://via.placeholder.com/100" width="100" height="100" x="0" y="0"/>
</svg>
```
这里我们定义了一个SVG路径(`<path>`),并将其分配一个`id`。然后我们添加了一个图像(`<image>`),并将其分配一个`id`,并使用`xlink:href`属性指定它的图像。在这里,我们使用占位符图像。
CSS代码:
```css
#myImage {
transform: translate(-50%, -50%);
}
```
在这里,我们对图像应用了`transform`,以便它始终居中。
JavaScript代码:
```javascript
const motionPath = document.getElementById("motionPath");
const myImage = document.getElementById("myImage");
// 获取路径总长度
const pathLength = motionPath.getTotalLength();
// 设置图像起始位置
myImage.setAttribute("x", motionPath.getPointAtLength(0).x);
myImage.setAttribute("y", motionPath.getPointAtLength(0).y);
// 设置动画
const animation = myImage.animate(
[
{ offsetDistance: "0%", transform: "translate(-50%, -50%)" },
{ offsetDistance: "100%", transform: `translate(${pathLength}px, -50%)` }
],
{
duration: 5000,
easing: "linear",
iterations: Infinity
}
);
// 更新图像位置
animation.currentTime = animation.effect.getTiming().duration / pathLength * myImage.x.baseVal.value;
animation.playbackRate = 1;
animation.addEventListener("finish", () => {
animation.currentTime = 0;
});
```
在这里,我们首先获取了路径的总长度,并将图像的起始位置设置为路径的第一个点。然后,我们使用`animation()`方法创建了一个动画,它将图像沿着路径运动。我们使用`offsetDistance`属性来控制动画的进度,并使用`transform`属性来移动图像。最后,我们更新了动画的当前时间,以便图像从正确的位置开始运动,并附加了一些事件句柄来处理动画完成时的情况。
这个示例展示了一个基本的图像沿着SVG路径运动的例子,但是您可以使用更复杂的路径和动画来创造更具吸引力的效果。