js获取视频某一帧

export function getVideoImage(videoUrl, duration) {
  return new Promise((resolve, reject) => {
    const video = document.createElement("video");
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");

    // 加载视频
    video.crossOrigin = "anonymous"; // 处理跨域
    video.src = videoUrl;
    video.preload = "auto";
    video.addEventListener("loadeddata", () => {
      // 设置 canvas 尺寸与视频一致
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;

      // 在 canvas 中绘制视频第一帧
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

      // 获取绘制的图像数据
      const imageData = canvas.toDataURL("image/png");

      // 释放资源
      URL.revokeObjectURL(video.src);
      resolve(imageData);
    });

    video.addEventListener("error", (error) => {
      reject(error);
    });

    // 加载视频元信息
    video.addEventListener("loadedmetadata", () => {
      // 设置视频播放时长
      const videoDuration = video.duration;
      // 将视频播放时间设置为 duration
      if (duration && videoDuration > duration) {
        video.currentTime = duration;
      }
    });
  });
}

你可能感兴趣的:(javascript,javascript,音视频,开发语言)