在 Vue 3 中,可以通过监听滚动事件和调整 SVG 的视口属性来实现 SVG 的缩放。以下是一个简单的例子,展示了如何在鼠标滚动时改变 SVG 的大小:
| <template> | |
| <div class="svg-container" @wheel="handleWheel"> | |
| <svg :viewBox="viewBox"> | |
| <!-- SVG内容 --> | |
| <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /> | |
| </svg> | |
| </div> | |
| </template> | |
| <script setup> | |
| import { ref } from 'vue'; | |
| const viewBox = ref('0 0 100 100'); | |
| function handleWheel(event) { | |
| event.preventDefault(); | |
| const scale = event.deltaY > 0 ? 1.1 : 0.9; // 根据滚轮方向来决定放大或缩小的比例 | |
| const [x, y, width, height] = viewBox.value.split(' ').map(Number); | |
| const newWidth = width * scale; | |
| const newHeight = height * scale; | |
| viewBox.value = `${x} ${y} ${newWidth} ${newHeight}`; | |
| } | |
| </script> | |
| <style> | |
| .svg-container { | |
| width: 500px; | |
| height: 500px; | |
| overflow: hidden; | |
| } | |
| svg { | |
| width: 100%; | |
| height: 100%; | |
| } | |
| </style> | 
 在这个例子中,我们创建了一个带有 svg-container 类的 div 来包裹 SVG 元素,并且给这个 div 添加了一个鼠标滚动事件监听器 @wheel 。在 handleWheel 函数中,我们根据鼠标滚轮的滚动方向 (event.deltaY) 来决定是放大还是缩小 SVG,并且更新 viewBox 的值来改变 SVG 的视口大小。这样,当用户滚动鼠标时,SVG 将相应地放大或缩小。
