---
title: "useMapAnimation"
description: "地图帧动画原语，基于 requestAnimationFrame，仅在地图首次 load 之后且样式已解析时调用回调。"
canonical_url: "https://maplibre.mhaibaraai.cn/docs/composables/use-map-animation"
---
# useMapAnimation

> 地图帧动画原语，基于 requestAnimationFrame，仅在地图首次 load 之后且样式已解析时调用回调。

## 简介

`useMapAnimation` 是地图帧动画原语：基于 `useRafFn`（组件卸载自动停止），仅在地图首次 `load` 之后且样式已解析时调用 `frame` 回调，回调第二参为自启动起的累计毫秒数，第三参为与上一帧的间隔毫秒数。动效组件与帧驱动图片均复用它。返回 `pause` / `resume` / `isActive` 控制运行状态。

> [!NOTE]
> 
> 在 
> 
> <MaplibreMap>
> 
>  子树外使用时经 
> 
> options.mapId
> 
>  指定目标地图。回调内每帧执行，避免在其中创建新对象或做重计算。

> [!TIP]
> 
> 首次 
> 
> load
> 
>  前不出帧，避免逐帧改样式推迟 
> 
> load
> 
>  事件；此后门控只看样式是否解析完成，不等待瓦片与源加载：拖动、缩放或每帧 
> 
> setData
> 
>  时动画不会跳帧。按时间推进的场景（如轨迹回放）用 
> 
> deltaMs
> 
>  累加，无需自行记录上一帧时间。

## 用法

每帧驱动 `circle-radius` 周期脉动：

```vue [UseMapAnimationExample.vue]
<script setup lang="ts">
import type { FeatureCollection } from 'geojson'

const mapId = 'use-map-animation-demo'

const data: FeatureCollection = {
  type: 'FeatureCollection',
  features: [
    { type: 'Feature', properties: {}, geometry: { type: 'Point', coordinates: [116.397, 39.908] } }
  ]
}

// 每帧驱动 circle-radius 周期脉动；图层未就绪时跳过
useMapAnimation((map, elapsed) => {
  if (!map.getLayer('pulse')) return
  map.setPaintProperty('pulse', 'circle-radius', 14 + 8 * Math.sin(elapsed / 400))
}, { mapId })
</script>

<template>
  <div class="h-115 w-full overflow-hidden rounded-(--ui-radius) border border-default">
    <MaplibreMap :map-id="mapId" :options="{ style: 'https://tiles.openfreemap.org/styles/dark', center: [116.397, 39.908], zoom: 12 }">
      <MaplibreLayer
        layer-id="pulse"
        type="circle"
        :source="{ type: 'geojson', data }"
        :paint="{ 'circle-color': '#22d3ee', 'circle-opacity': 0.6, 'circle-radius': 14 }"
      />
    </MaplibreMap>
  </div>
</template>
```

## API

### `useMapAnimation()`

创建帧动画循环。

**frame** (`(map: Map, elapsedMs: number, deltaMs: number) => void`) *required*: 每帧回调；elapsedMs 为自启动起的累计毫秒数，deltaMs 为与上一帧的间隔毫秒数。

**options.mapId** (`string`): 目标地图 id；在 <MaplibreMap> 子树外使用时必填。

**options.immediate** (`boolean`): 创建后立即启动，默认 true。

返回 `UseMapAnimationReturn`：

**pause** (`() => void`): 暂停动画。

**resume** (`() => void`): 恢复动画。

**isActive** (`Readonly<Ref<boolean>>`): 是否正在运行。

## Changelog

See commit history for [src/runtime/composables/useMapAnimation.ts](https://github.com/mhaibaraai/movk-maplibre/commits/main/src/runtime/composables/useMapAnimation.ts).


## Sitemap

See the full [sitemap](https://maplibre.mhaibaraai.cn/sitemap.md) for all pages.
