You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

wavesurfer.js容器应用transform:scale缩放后点击跳转位置偏移如何修复

问题原因

wavesurfer.js v2版本内部计算点击跳转坐标时,仅使用了容器原始像素尺寸,未识别外层元素的transform: scale缩放属性,导致点击像素换算音频进度时出现比例偏差,最终跳转位置和点击位置不一致。

修复方案

保留外层容器缩放能力的前提下,关闭wavesurfer默认交互逻辑,手动计算适配缩放系数的点击进度即可,支持缩放数值动态调整。

完整修改代码

JavaScript修改

// 获取外层容器当前缩放系数
function getContainerScale() {
  const container = document.querySelector('.container')
  const transformStyle = window.getComputedStyle(container).transform
  const transformMatrix = new DOMMatrix(transformStyle)
  return transformMatrix.a
}

const wavesurfer = WaveSurfer.create({
     container: document.querySelector(`#waveform`),
     backend: 'MediaElement',
     waveColor: '#525054',
     progressColor: '#eb7100',
     cursorColor: 'transparent',
     height: 450,
     fillParent: true,
     minPxPerSec: 100,
     hideScrollbar: true,
     // 关闭默认点击交互,避免冲突
     interact: false
});
wavesurfer.load(`https://ia902606.us.archive.org/35/items/shortpoetry_047_librivox/song_cjrg_teasdale_64kb.mp3`);

// 绑定自定义点击跳转逻辑
document.querySelector('#waveform').addEventListener('click', (e) => {
  const waveformRect = e.currentTarget.getBoundingClientRect()
  // 计算点击位置相对波形左侧的像素距离
  const relativeClickX = e.clientX - waveformRect.left
  // 适配缩放系数,得到原始像素对应的点击位置
  const adjustedClickX = relativeClickX / getContainerScale()
  // 换算为0-1范围的进度值,做边界校验
  const progress = Math.min(1, Math.max(0, adjustedClickX / waveformRect.width))
  wavesurfer.seekTo(progress)
})

// 如果缩放数值会动态调整,每次修改缩放后调用以下方法重绘波形,避免显示错位
// wavesurfer.drawBuffer()

原有CSS、HTML代码无需修改。

内容的提问来源于stack exchange,提问作者Sara Ree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 20:36:04