<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500" width="500" height="500"> <!-- 创建路径和光标 --> <path id="drawingPath" d="M50 50 L100 200 Q200 50 300 100 L400 200 L450 450" fill="none" stroke="#000" stroke-width="2"/> <circle id="cursor" r="5" fill="red"/> <script> // 获取路径元素和光标元素 const drawingPath = document.getElementById('drawingPath'); const cursor = document.getElementById('cursor'); // 获取路径的总长度 const pathLength = drawingPath.getTotalLength(); // 设置路径的样式,初始状态为不可见 drawingPath.style.strokeDasharray = pathLength; drawingPath.style.strokeDashoffset = pathLength; // 设置光标初始位置 const startPoint = drawingPath.getPointAtLength(0); cursor.setAttribute('cx', startPoint.x); cursor.setAttribute('cy', startPoint.y); // 启动动画 function startDrawingAnimation() { drawingPath.style.transition = 'stroke-dashoffset 4s linear'; drawingPath.style.strokeDashoffset = '0'; // 实时更新光标位置 let animationStartTime; function updateCursor(timestamp) { if (!animationStartTime) animationStartTime = timestamp; const elapsed = timestamp - animationStartTime; const progress = elapsed / 4000; // 4秒动画时间 const distance = progress * pathLength; // 更新光标位置 const point = drawingPath.getPointAtLength(distance); cursor.setAttribute('cx', point.x); cursor.setAttribute('cy', point.y); // 继续动画 if (progress < 1) { requestAnimationFrame(updateCursor); } } // 开始光标位置更新动画 requestAnimationFrame(updateCursor); } // 延时启动动画 setTimeout(startDrawingAnimation, 500); </script> </svg>
发表评论