# @100mslive/hms-virtual-background 中文文档

规范地址：https://npmcn.com/package/%40100mslive/hms-virtual-background/

版本：1\.16\.3
npm 元数据更新时间：2026-09-30T17:35:21.807Z
中文译文更新时间：2026-11-05T18:13:39.802Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40100mslive/hms-virtual-background
原文对照：https://npmcn.com/package/%40100mslive/hms-virtual-background/?lang=original
项目主页：https://github.com/100mslive/web-sdks#readme
源码仓库：https://github.com/100mslive/web-sdks

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：4.6 MB，28 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：10 个
- peer 依赖：@100mslive/hms-video-store 0\.15\.3
- 首次发布：2021-04-13T07:27:53.412Z
- 最新版本发布：2026-09-30T17:35:21.439Z
- 近 30 天下载量：93400（2026-10-04 至 2026-11-02，npm 官方下载统计）
- 已发布版本数：677（近 12 个月 81 个）

## 中文简介

[![Lint, Test and Build](https://github.com/100mslive/web-sdks/actions/workflows/lint-test-build.yml/badge.svg)](https://github.com/100mslive/web-sdks/actions/workflows/lint-test-build.yml) \[!\]\[Bundle Size\] (https://badgen.net/bundle Phobiado/minzip/@100mslive\] (中文(简体) )

## 安装

```sh
npm install @100mslive/hms-virtual-background
```

也可以使用：`pnpm add @100mslive/hms-virtual-background`、`yarn add @100mslive/hms-virtual-background`、`bun add @100mslive/hms-virtual-background`

## README

# 具有SDK效果的虚拟背景

[![Lint, Test and Build](https://github.com/100mslive/web-sdks/actions/workflows/lint-test-build.yml/badge.svg)](https://github.com/100mslive/web-sdks/actions/workflows/lint-test-build.yml) [![Bundle Size](https://badgen.net/bundlephobia/minzip/@100mslive/hms-virtual-background)](https://bundlephobia.com/result?p=@100mslive/hms-virtual-background) [![License](https://img.shields.io/npm/l/@100mslive/hms-virtual-background)](https://www.100ms.live/) ![Tree shaking](https://badgen.net/bundlephobia/tree-shaking/@100mslive/hms-virtual-background)

虚拟背景插件有助于自定义自己的背景 。 自定义选项正在模糊背景或被静态图像所取代. 本指南概述了100ms虚拟背景插件的使用.

## 先决条件

获取100ms VirtualBackground软件包\*\*(自1.11.28版本起支持)

```bash
npm install --save @100mslive/hms-virtual-background@latest
```

## 特征

以下特性目前得到以下 `HMSEffectsPlugin` 类 :

```js
/**
 * Sets the blur intensity.
 * @param {number} blur - The blur intensity, ranging from 0 to 1.
 * @returns {void}
 */
setBlur(blur) {}

/**
 * Sets the virtual background using the provided media URL.
 * @param {HMSEffectsBackground} url - The media URL to set as the virtual background.
 * Alternatively, the background image can be downloaded beforehand and passed to setBackground as objectURL
 * @returns {void}
 */
setBackground(url) {}

/**
 * Retrieves the name of the plugin.
 * @returns {string} The name of the plugin, 'HMSEffects'.
 */
getName() {}

/**
 * Retrieves the currently enabled background type or media URL.
 * @returns {string|MediaStream|MediaStreamTrack|HTMLVideoElement} The background type or media URL.
 */
getBackground() {}

/**
 * Sets the preset quality of the virtual background.
 * Options:  "balanced" | "quality"
 * The 'quality' preset has a higher CPU usage than the 'balanced' preset which is the default
 * @param {string} preset - The preset quality to set.
 * @returns {Promise<void>}
 */
setPreset(preset) {}

/**
 * Retrieves the active preset quality of the virtual background.
 * @returns {string} The active preset quality.
 */
getPreset() {}

/**
 * Clears all applied filters.
 * @returns {void}
 */
removeEffects() {}

/**
 * Stops the plugin.
 * @returns {void}
 */
stop() {}

```

插件支持的回调 :

在初始化时, 插件下载所需资源后:

```
const effectsPlugin = new HMSEffectsPlugin(<key>, () => console.log("Plugin initialised"));

```

在分辨率变化( 在设备旋转或视频宽度比变化时) :

```
effectsPlugin.onResolutionChange = (width: number, height: number) => {
  console.log(`Resolution changed to ${width}x${height}`)
}
```

## 证明虚拟背景

效果的 SDK 键需要用于即时 `HMSEffectsPlugin` 类 :

```jsx
  const effectsKey = useHMSStore(selectEffectsKey);
```

建议在单独的文件中初始化对象,以防止在重报时多次初始化,并保持UI级别代码独立于SDK的内部调用.

```js
import { HMSEffectsPlugin, HMSVirtualBackgroundTypes } from '@100mslive/hms-virtual-background';

export class VBPlugin {
  private effectsPlugin?: HMSEffectsPlugin | undefined;

  initialisePlugin = (effectsSDKKey?: string) => {
    if (this.getVBObject()) {
      return;
    }
    if (effectsSDKKey) {
      this.effectsPlugin = new HMSEffectsPlugin(effectsSDKKey);
    }
  };

  getBackground = () => {
    return this.effectsPlugin?.getBackground();
  };

  getBlurAmount = () => {
    return this.effectsPlugin?.getBlurAmount();
  };

  getVBObject = () => {
    return this.effectsPlugin;
  };

  getName = () => {
    return this.effectsPlugin?.getName();
  };

  setBlur = async (blurPower: number) => {
    this.effectsPlugin?.setBlur(blurPower);
  };

  setBackground = async (mediaURL: string) => {
    this.effectsPlugin?.setBackground(mediaURL);
  };

  setPreset = (preset: string) => {
    this.effectsPlugin.setPreset(preset);
  };

  getPreset = () => {
    return this.effectsPlugin?.getPreset() || '';
  };

  removeEffects = async () => {
    this.effectsPlugin?.removeEffects();
  };

  reset = () => {
    this.effectsPlugin = undefined;
  };
}

export const VBHandler = new VBPlugin();
```

## 建设UI

以下片段说明了如何将插件添加到视频中并管理UI状态以保存配置:

```jsx
import {
  selectEffectsKey,
  selectIsLocalVideoPluginPresent
  selectLocalVideoTrackID,
  useHMSStore,
} from '@100mslive/react-sdk';
import { 
  HMSEffectsPlugin, 
  HMSVirtualBackgroundTypes
} from '@100mslive/hms-virtual-background';
import { VBHandler } from './VBHandler';

export const VirtualBackgroundPicker = () => {
  const hmsActions = useHMSActions();
  // Get the effects SDK key here
  const effectsKey = useHMSStore(selectEffectsKey);
  const trackId = useHMSStore(selectLocalVideoTrackID);
  const isPluginAdded = useHMSStore(selectIsLocalVideoPluginPresent(VBHandler?.getName() || ''));
  
  // State can be used to show active selection
  const [background, setBackground] = useState<string | HMSVirtualBackgroundTypes>(
    VBHandler.getBackground() as string | HMSVirtualBackgroundTypes,
  );

  useEffect(() => {
    if (!track?.id) {
      return;
    }
    if (!isPluginAdded) {
      let vbObject = VBHandler.getVBObject();
      if (!vbObject) {
        VBHandler.initialisePlugin(effectsKey);
        vbObject = VBHandler.getVBObject();
        if (effectsKey) {
          hmsActions.addPluginsToVideoStream([vbObject as HMSEffectsPlugin]);
        } 
      }
    }
  }, [hmsActions, isPluginAdded, effectsKey, track?.id]);

  // UI code for media picker can go here
}

```

这处理初始化,并在视频流中添加插件. 插件在初始化过程中第一次负载需要几秒钟. 随后的过滤和效果选择应花不到一秒钟的时间来反映.

这些方法可以通过 `VBHandler` 对象 :

```jsx
const setBackground = async(mediaURL : string) => {
  await VBHandler?.setBackground(mediaURL);
  // The selection can be highlighted using the activeBackground state
  setActiveBackground(mediaURL);
}

const setBlur = async(blurAmount: number) => {
  await VBHandler?.setBlur(blurAmount);
  setActiveBackground(HMSVirtualBackgroundTypes.BLUR);
}

const removeEffects = async() => {
  await VBHandler.removeEffects();
  setActiveBackground(HMSVirtualBackgroundTypes.NONE);
}
```

可在下文中看到全面执行《公约》的情况 [房间基特反应包](https://github.com/100mslive/web-sdks/blob/main/packages/roomkit-react/src/Prebuilt/components/VirtualBackground/VBPicker.tsx)。 。 。 .

## 支持的浏览器

效果虚拟背景在基于Safari,Firefox和Chromium的浏览器上得到支持.

## 常见问题

### @100mslive/hms-virtual-background 是什么？

\[\!\]\[Bundle Size\] \(https://badgen\.net/bundle Phobiado/minzip/@100mslive\] \(中文\(简体\) \)

### 如何安装 @100mslive/hms-virtual-background？

在项目目录运行 npm install @100mslive/hms-virtual-background，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@100mslive/hms-video-store（0\.15\.3）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @100mslive/hms-virtual-background 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @100mslive/hms-virtual-background 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @100mslive/hms-virtual-background 可以商用吗？

@100mslive/hms-virtual-background 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @100mslive/hms-virtual-background 的下载量有多少？

根据 npm 官方下载统计，@100mslive/hms-virtual-background 在 2026/10/04 – 2026/11/02 这 30 天内被下载 93,400 次，日均约 3,113 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @100mslive/hms-virtual-background 还在维护吗？

最新版本 1\.16\.3 发布于 2026/10/01（1 个月前）；至今共发布 677 个版本，其中过去 12 个月发布了 81 个；首次发布于 2021/04/13。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

