animation.vue 11.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
<!--
 * @Date: 2025-03-28 09:23:04
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-03-28 21:56:54
 * @FilePath: /mlaj/src/views/animation.vue
 * @Description: 贝塞尔曲线动画路径组件
 *
 * 该组件实现了一个基于SVG的贝塞尔曲线动画效果:
 * 1. 在画布上展示多个连接点
 * 2. 点击"下一步"按钮可以逐步显示连接点之间的贝塞尔曲线路径
 * 3. 路径带有动画效果和箭头指示方向
 * 4. 已激活的路径段会以绿色高亮显示
-->
<template>
  <div class="animation-container">
    <div style="position: fixed; top: 100px; right: 0; z-index: 999;">
      <button
        class="next-button"
        @click="nextStep"
        :disabled="activeNodeIndex >= points.length - 1"
      >
        下一步
      </button>
    </div>
    <svg
      width="100%"
      height="100%"
      :viewBox="svgViewBox"
      class="animation-svg"
      preserveAspectRatio="xMidYMid meet"
    >
      <!-- 定义箭头标记 -->
      <defs>
        <marker
          id="arrow-inactive"
          viewBox="0 0 10 10"
          refX="5"
          refY="5"
          markerWidth="6"
          markerHeight="6"
          orient="auto-start-reverse"
        >
          <path d="M 0 0 L 10 5 L 0 10 z" fill="#ccc" />
        </marker>
        <marker
          id="arrow-active"
          viewBox="0 0 10 10"
          refX="5"
          refY="5"
          markerWidth="6"
          markerHeight="6"
          orient="auto-start-reverse"
        >
          <path d="M 0 0 L 10 5 L 0 10 z" fill="#4CAF50" />
        </marker>
      </defs>

      <!-- 贝塞尔曲线路径 -->
      <template v-for="(_, index) in points.slice(0, -1)" :key="index">
        <path
          v-show="activeNodeIndex === -1 || index > activeNodeIndex"
          :d="calculatePathSegment(points[index], points[index + 1])"
          fill="none"
          :stroke="pathColor"
          stroke-width="2"
          stroke-dasharray="5,5"
          class="path-animation"
          marker-end="url(#arrow-inactive)"
        />
      </template>

      <!-- 高亮的路径段 -->
      <path
        v-for="(segment, index) in activePathSegments"
        :key="index"
        :d="segment"
        fill="none"
        stroke="#4CAF50"
        stroke-width="2"
        stroke-dasharray="10"
        marker-end="url(#arrow-active)"
        class="active-path-animation"
      />

      <!-- 节点圆点 -->
      <template v-for="(point, index) in points" :key="index">
        <circle
          :cx="point.x"
          :cy="point.y"
          r="12"
          :class="['node', { 'node-active': activeNodeIndex >= index - 1 }]"
        />
      </template>

      <!-- Image In Svg -->
      <template v-for="(obj, index) in svgObj" :key="obj.name">
        <image
          :id="obj.name"
          :href="index <= activeNodeIndex ? obj.light_up : obj.not_light"
          width="100"
          height="100"
          :x="points[0].x + obj.offset.x"
          :y="points[0].y + obj.offset.y"
        />
      </template>
    </svg>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import img_svg1 from "@/assets/1.svg";
import img_svg2 from "@/assets/2.svg";
import img_svg3 from "@/assets/3.svg";
import img_svg4 from "@/assets/4.svg";
import img_svg5 from "@/assets/5.svg";

// 定义节点坐标数组,每个节点包含x和y坐标
// 这些点将用于生成贝塞尔曲线的路径
const points = ref([
  { x: 700, y: 50 },
  { x: 300, y: 300 },
  { x: 700, y: 600 },
  { x: 300, y: 800 },
  { x: 700, y: 1000 },
]);

// 当前激活的节点索引,初始值为-1表示没有节点被激活
const activeNodeIndex = ref(-1);

// 存储已激活的路径段数组,每个元素是一个SVG路径字符串
// 用于显示高亮的贝塞尔曲线路径
const activePathSegments = ref([]);

// 计算完整的贝塞尔曲线路径
// 使用三次贝塞尔曲线(Cubic Bezier)创建平滑的曲线效果
// 控制点的位置通过当前点和下一个点的中点来计算
const pathData = computed(() => {
  const path = [];
  points.value.forEach((point, index) => {
    if (index === 0) {
      path.push(`M ${point.x} ${point.y}`);
    } else {
      const prevPoint = points.value[index - 1];
      const segment = calculatePathSegment(prevPoint, point);
      path.push(segment.substring(segment.indexOf("C")));
    }
  });
  return path.join(" ");
});

// 计算两点之间的贝塞尔曲线路径段
// @param startPoint - 起始点坐标 {x, y}
// @param endPoint - 结束点坐标 {x, y}
// @returns 返回SVG路径字符串
const calculatePathSegment = (startPoint, endPoint) => {
  // 计算路径的方向向量
  const dx = endPoint.x - startPoint.x;
  const dy = endPoint.y - startPoint.y;
  const distance = Math.sqrt(dx * dx + dy * dy);

  // 设置节点间的偏移距离(可以根据需要调整)
  const offset = 0;
  const verticalOffset = -30; // 添加垂直偏移量参数

  // 计算单位向量
  const unitX = dx / distance;
  const unitY = dy / distance;

  // 计算偏移后的起点和终点,根据路径方向调整垂直偏移
  const adjustedStart = {
    x: startPoint.x + unitX * offset,
    y: startPoint.y + (dy > 0 ? -verticalOffset : verticalOffset),
  };
  const adjustedEnd = {
    x: endPoint.x - unitX * offset,
    y: endPoint.y + (dy > 0 ? verticalOffset : -verticalOffset),
  };

  // 计算控制点
  const cpx1 = adjustedStart.x;
  const cpy1 = adjustedStart.y + (adjustedEnd.y - adjustedStart.y) * 0.5;
  const cpx2 = adjustedEnd.x;
  const cpy2 = adjustedStart.y + (adjustedEnd.y - adjustedStart.y) * 0.5;

  return `M ${adjustedStart.x} ${adjustedStart.y} C ${cpx1} ${cpy1}, ${cpx2} ${cpy2}, ${adjustedEnd.x} ${adjustedEnd.y}`;
};

// 未激活路径的颜色
// 使用浅灰色(#ccc)表示未激活状态
const pathColor = computed(() => {
  return "#ccc";
});

// 处理节点点击事件,激活指定节点并更新路径
// @param index - 被点击节点的索引
// 点击节点时会激活该节点及其之前的所有节点和路径
// const activateNode = (index) => {
//   activeNodeIndex.value = index;
//   activePathSegments.value = [];

//   // 重新计算所有激活的路径段
//   for (let i = 0; i < index; i++) {
//     const startPoint = points.value[i];
//     const endPoint = points.value[i + 1];
//     if (endPoint) {
//       const segment = calculatePathSegment(startPoint, endPoint);
//       activePathSegments.value.push(segment);
//     }
//   }
// };

// 处理下一步按钮点击事件
// 激活下一个节点并创建新的高亮路径段
// 当到达最后一个节点时,按钮将被禁用
const nextStep = () => {
  if (activeNodeIndex.value < points.value.length - 1) {
    activeNodeIndex.value++;
    const startPoint = points.value[activeNodeIndex.value];
    const endPoint = points.value[activeNodeIndex.value + 1];
    // 只有当存在下一个节点时才添加新的路径段
    if (endPoint) {
      const newSegment = calculatePathSegment(startPoint, endPoint);
      // 保留之前的路径段,添加新的路径段
      activePathSegments.value.push(newSegment);
    }
    // 如果是最后一个节点,直接将其设置为激活状态
    if (activeNodeIndex.value === points.value.length - 1) {
      activeNodeIndex.value = points.value.length - 1;
    }
  }
};

// 图片对象数组
const svgObj = [
  {
    name: "node1",
    not_light: img_svg1,
    light_up: img_svg5,
    offset: {
      x: -350,
      y: -25,
    },
  },
  {
    name: "node2",
    not_light: img_svg2,
    light_up: img_svg4,
    offset: {
      x: -150,
      y: 200,
    },
  },
  {
    name: "node3",
    not_light: img_svg3,
    light_up: img_svg3,
    offset: {
      x: -450,
      y: 480,
    },
  },
  {
    name: "node4",
    not_light: img_svg4,
    light_up: img_svg2,
    offset: {
      x: -150,
      y: 700,
    },
  },
  {
    name: "node5",
    not_light: img_svg5,
    light_up: img_svg1,
    offset: {
      x: -450,
      y: 950,
    },
  },
];
// 计算SVG容器尺寸
const containerSize = computed(() => {
  const container = document.querySelector('.animation-container');
  if (!container) return { width: 0, height: 0 };
  return {
    width: container.clientWidth,
    height: container.clientHeight
  };
});

// 监听窗口大小变化
const updateContainerSize = () => {
  containerSize.value = {
    width: document.querySelector('.animation-container')?.clientWidth || 0,
    height: document.querySelector('.animation-container')?.clientHeight || 0
  };
};

onMounted(() => {
  updateContainerSize();
  window.addEventListener('resize', updateContainerSize);
});

onUnmounted(() => {
  window.removeEventListener('resize', updateContainerSize);
});

// 更新svgViewBox计算属性
const svgViewBox = computed(() => {
  const maxX = Math.max(...points.value.map(p => p.x));
  const maxY = Math.max(...points.value.map(p => p.y));
  const minX = Math.min(...points.value.map(p => p.x));
  const minY = Math.min(...points.value.map(p => p.y));
  const padding = 100;

  // 计算内容的宽高比
  const contentWidth = maxX - minX + padding * 2;
  const contentHeight = maxY - minY + padding * 2;
  const contentRatio = contentWidth / contentHeight;

  // 获取容器的宽高比
  const containerRatio = containerSize.value.width / containerSize.value.height;

  // 根据宽高比调整viewBox
  if (containerRatio > contentRatio) {
    // 容器更宽,以高度为基准
    const adjustedWidth = contentHeight * containerRatio;
    const extraPadding = (adjustedWidth - contentWidth) / 2;
    return `${minX - padding - extraPadding} ${minY - padding} ${adjustedWidth} ${contentHeight}`;
  } else {
    // 容器更高,以宽度为基准
    const adjustedHeight = containerRatio ? contentWidth / containerRatio : contentHeight;
    const extraPadding = isFinite(adjustedHeight) ? (adjustedHeight - contentHeight) / 2 : 0;
    return `${minX - padding} ${minY - padding - extraPadding} ${contentWidth} ${adjustedHeight}`;
  }
});
</script>

<style scoped>
.animation-container {
  position: relative;
  width: 100%;
  height: 100vh;
  background: #f5f5f5;
  padding: 1rem;
  box-sizing: border-box;
  overflow: hidden;
}

.animation-svg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  margin: 0;
  display: block;
}

@media screen and (max-width: 768px) {
  .animation-container {
    padding: 0.5rem;
  }

  .animation-svg {
    width: 100%;
    height: auto;
    min-height: 90vh;
  }

  .next-button {
    padding: 0.5rem 1rem;
    font-size: 1rem;
  }
}

.node {
  fill: white;
  stroke: #ccc;
  stroke-width: 0.125rem;
  cursor: pointer;
  transition: all 0.3s ease;
}

.node-active {
  fill: white;
  stroke: #4caf50;
}

.path-animation {
  transition: all 0.5s ease;
}

.active-path-animation {
  animation: dash 1.5s linear infinite;
}

@keyframes dash {
  to {
    stroke-dashoffset: -1.25rem;
  }
}

.next-button {
  position: absolute;
  top: 1.25rem;
  right: 1.25rem;
  padding: 0.5rem 1rem;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 0.25rem;
  cursor: pointer;
  transition: all 0.3s ease;
}

.next-button:hover {
  background-color: #45a049;
}

.next-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}
</style>