index.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. /**
  2. * 一行谱动画
  3. */
  4. import { watch, ref, Ref, h, render } from "vue"
  5. import { getAudioCurrentTime } from "/src/view/audio-list"
  6. import state from "/src/state"
  7. import "./index.less"
  8. import Bird from "./bird"
  9. type pointsPosType = { x: number; y: number; MeasureNumberXML: number; noteId: number }[]
  10. type smoothAnimationType = {
  11. isShow: Ref<boolean>
  12. canvasDom: null | HTMLCanvasElement
  13. canvasCtx: null | undefined | CanvasRenderingContext2D
  14. canvasDomWith: number
  15. canvasDomHeight: number
  16. canvasSmoothDom: null | HTMLCanvasElement
  17. smoothAnimationBoxDom: null | HTMLElement
  18. smoothBotDom: null | HTMLElement
  19. osmdCanvasPageDom: null | HTMLElement
  20. osdmScrollDom: null | HTMLElement
  21. osdmScrollDomWith: number
  22. osdmScrollDomOffsetLeft: number
  23. selectionBoxDom: null | HTMLElement
  24. selectionBgBoxDom: null | HTMLElement
  25. batePos: pointsPosType
  26. pointsPos: pointsPosType
  27. translateXNum: number
  28. aveSpeed: number,
  29. pageTurnLock: boolean
  30. oldCurrentTime: number
  31. }
  32. let _numberOfSegments = 56 // 中间切割线的个数
  33. const _canvasDomHeight = 60 // canvans 高度
  34. export const smoothAnimationState = {
  35. isShow: ref(false), // 是否显示
  36. canvasDom: null,
  37. canvasCtx: null,
  38. canvasDomWith: 0,
  39. canvasDomHeight: _canvasDomHeight,
  40. canvasSmoothDom: null,
  41. smoothAnimationBoxDom: null,
  42. smoothBotDom: null,
  43. osmdCanvasPageDom: null,
  44. osdmScrollDom: null,
  45. osdmScrollDomWith: 0,
  46. osdmScrollDomOffsetLeft: 0,
  47. selectionBoxDom: null,
  48. selectionBgBoxDom: null,
  49. batePos: [], // times 直接转换的数组
  50. pointsPos: [], // 筛选之后的点坐标数组
  51. translateXNum: 0, // 当前谱面的translateX的距离 谱面的位置信息 由translateX和scrollLeft的偏移一起决定
  52. aveSpeed: 0, // 谱面的一帧的平均速度
  53. pageTurnLock: false,
  54. oldCurrentTime: 0
  55. } as smoothAnimationType
  56. // 监听显示与隐藏
  57. watch(smoothAnimationState.isShow, () => {
  58. if (smoothAnimationState.isShow.value) {
  59. smoothAnimationState.smoothAnimationBoxDom?.classList.remove("smoothAnimationBoxHide")
  60. } else {
  61. smoothAnimationState.smoothAnimationBoxDom?.classList.add("smoothAnimationBoxHide")
  62. }
  63. })
  64. /**
  65. * 初始化
  66. */
  67. export function initSmoothAnimation() {
  68. // 创建dom
  69. createSmoothAnimation()
  70. // 初始化动画数据
  71. const batePos = getPointsPosByBatePos()
  72. smoothAnimationState.batePos = batePos
  73. const batePos1 = dataFilter([...batePos])
  74. console.log(batePos1, "排序之后的数据")
  75. // 这里性能优化,对于超级长的曲子,_numberOfSegments值 动态变化
  76. const numberOfSegments = parseInt(16000 / batePos1.length + "")
  77. _numberOfSegments = Math.max(18, Math.min(_numberOfSegments, numberOfSegments))
  78. const batePos2 = createSmoothCurvePoints(batePos1, _numberOfSegments)
  79. smoothAnimationState.pointsPos = batePos2
  80. // 初始化旋律线
  81. initCanvasSmooth()
  82. // 谱面的平均速度(因为可能有反复的情况所以实际距离要加上反复的距离)
  83. const canvasDomPath = batePos.reduce((path, item, index, arr) => {
  84. if (index !== 0) {
  85. if (Math.abs(item.MeasureNumberXML - arr[index - 1].MeasureNumberXML) <= 1) {
  86. path += item.x - arr[index - 1].x
  87. }
  88. }
  89. return path
  90. }, 0)
  91. // 20 是屏幕多长时间刷新一次的时间,本来是16.67的,但是有些手机帧率比较低,所以这里给小一点的值,宁愿慢一点偏屏幕左边一点
  92. smoothAnimationState.aveSpeed = (canvasDomPath / (state.times[state.times.length - 1].time - state.times[0].time) / 1000) * 20
  93. // 当前屏幕的宽度
  94. calcClientWidth()
  95. window.addEventListener("resize", calcClientWidth)
  96. // 初始化 只有练习模式 才显示
  97. state.modeType === "practise" && (smoothAnimationState.isShow.value = state.melodyLine)
  98. // 多分轨合并显示、打击乐、节奏练习的曲子不显示旋律线
  99. if (state.isCombineRender || state.isPercussion) {
  100. smoothAnimationState.isShow.value = false
  101. }
  102. console.log(smoothAnimationState, "一行谱小鸟数据")
  103. }
  104. // 排序
  105. function dataFilter(batePos: pointsPosType) {
  106. // 去掉反复跳房子的数据
  107. const filterData = batePos.filter((item, index, array) => {
  108. return array.findIndex(i => i.noteId === item.noteId) === index
  109. })
  110. // 先按 音符排序
  111. const sortedData = filterData.sort((a, b) => a.noteId - b.noteId)
  112. // 再按 小节排序
  113. return sortedData.sort((a, b) => a.MeasureNumberXML - b.MeasureNumberXML)
  114. }
  115. //根据 activeInde和进度 查找转换之后的activeInde
  116. function dataFindIndex(activeIndex: number, progress: number) {
  117. // 百分比转为当前的index 距离个数
  118. const progressCalcIndex = Math.round(progress * _numberOfSegments)
  119. const { noteId, MeasureNumberXML } = smoothAnimationState.batePos[activeIndex]
  120. return (
  121. smoothAnimationState.pointsPos.findIndex(item => {
  122. return item.noteId === noteId && item.MeasureNumberXML === MeasureNumberXML
  123. }) + progressCalcIndex
  124. )
  125. }
  126. /**
  127. * 销毁
  128. */
  129. export function destroySmoothAnimation() {
  130. smoothAnimationState.isShow.value = false
  131. window.removeEventListener("resize", calcClientWidth)
  132. // 销毁组件 防止内存泄漏
  133. smoothAnimationState.smoothBotDom && render(null, smoothAnimationState.smoothBotDom)
  134. smoothAnimationState.smoothAnimationBoxDom?.remove()
  135. Object.assign(smoothAnimationState, {
  136. canvasDom: null,
  137. canvasCtx: null,
  138. canvasDomWith: 0,
  139. canvasDomHeight: _canvasDomHeight,
  140. canvasSmoothDom: null,
  141. smoothAnimationBoxDom: null,
  142. smoothBotDom: null,
  143. osmdCanvasPageDom: null,
  144. osdmScrollDom: null,
  145. osdmScrollDomWith: 0,
  146. osdmScrollDomOffsetLeft: 0,
  147. selectionBoxDom: null,
  148. selectionBgBoxDom: null,
  149. batePos: [],
  150. pointsPos: [],
  151. translateXNum: 0,
  152. aveSpeed: 0,
  153. pageTurnLock: false,
  154. oldCurrentTime: 0
  155. })
  156. }
  157. /**
  158. * 根据播放时间进度移动处理
  159. * isIgnoreFilter 忽略这种 判断,因为有些只需要谱面移动
  160. */
  161. export function moveSmoothAnimationByPlayTime(time?: number, isIgnoreFilter = false) {
  162. // 暂停之后不进行移动了
  163. if (state.playState === "paused") {
  164. return
  165. }
  166. const currentTime = time || getAudioCurrentTime()
  167. // 某些浏览器 音频暂停后返回的时间会倒退,把这种时间过滤掉
  168. if(currentTime < smoothAnimationState.oldCurrentTime && !isIgnoreFilter) {
  169. return
  170. }
  171. smoothAnimationState.oldCurrentTime = currentTime
  172. if (currentTime <= state.fixtime) return
  173. if (currentTime > state.times.last()?.endtime) return
  174. // 当休止小节,可能当前音符在谱面上没有实际的音符(没有bbox),所以往后找谱面上有的音符
  175. const nextIndex = state.activeNoteIndex + 1
  176. // 当前的音符和下一个音符之间的时值 (当是最后一个音符的时候,下一个音符的时间取当前音符的endtime)
  177. const noteDuration =
  178. (nextIndex > state.times.length - 1 ? state.times[state.activeNoteIndex]?.endtime : state.times[nextIndex].time) -
  179. state.times[state.activeNoteIndex]?.time
  180. // 妙极客曲目 有可能2个音符时值一样
  181. if (noteDuration <= 0) {
  182. return
  183. }
  184. // 当前时值在该区间的占比
  185. let playProgress = (currentTime - state.times[state.activeNoteIndex]?.time) / noteDuration
  186. // 华为手机 fixtime 有个默认0.08的值,所以进度可能为负数 ,这里兼容一下
  187. playProgress < 0 && (playProgress = 0)
  188. moveSmoothAnimation(playProgress, state.activeNoteIndex)
  189. }
  190. /**
  191. * 移动处理
  192. * progress 当前音符到下一个音符的距离百分比
  193. * activeIndex 当前
  194. */
  195. export function moveSmoothAnimation(progress: number, activeIndex: number, isMoveOsmd = true) {
  196. // if (!smoothAnimationState.isShow.value) {
  197. // return
  198. // }
  199. const nowIndex = dataFindIndex(activeIndex, progress)
  200. const nowPointsPos = smoothAnimationState.pointsPos[nowIndex]
  201. // 当x的值为null和undefinedde的时候 错误 不走下面的方法
  202. if (!(nowPointsPos?.x != null)) {
  203. console.error(nowPointsPos?.x, "nowPointsPos", nowIndex, activeIndex)
  204. return
  205. }
  206. // 移动
  207. smoothAnimationMove(
  208. {
  209. x: nowPointsPos.x - 18, //鸟的大小
  210. y: nowPointsPos.y - 17
  211. },
  212. smoothAnimationState.pointsPos.slice(0, nowIndex)
  213. )
  214. // 当移动到屏幕最右边时候 就不进行移动了 存在移动到屏幕最右边时候 有反复的情况需要屏幕移动。所以这里注释掉了
  215. // if (
  216. // (smoothAnimationState.osdmScrollDom?.scrollLeft || 0) + smoothAnimationState.translateXNum + smoothAnimationState.osdmScrollDomWith >=
  217. // smoothAnimationState.canvasDomWith
  218. // ) {
  219. // return
  220. // }
  221. //isMoveOsmd && move_osmd(nowPointsPos)
  222. isMoveOsmd && pageTurn_osmd(nowPointsPos)
  223. }
  224. /**
  225. * 谱面翻页逻辑
  226. */
  227. function pageTurn_osmd(nowPointsPos: pointsPosType[0]) {
  228. if (smoothAnimationState.pageTurnLock) return
  229. // 视口宽度
  230. const clientWidth = smoothAnimationState.osdmScrollDomWith
  231. let { left, right } = smoothAnimationState.smoothBotDom!.getBoundingClientRect()
  232. left -= smoothAnimationState.osdmScrollDomOffsetLeft
  233. right -= smoothAnimationState.osdmScrollDomOffsetLeft
  234. if (right > clientWidth || left < 0) {
  235. // 移动超过屏幕时候;移动小于屏幕时候
  236. smoothAnimationState.translateXNum = 0
  237. smoothAnimationState.osdmScrollDom!.scrollLeft = nowPointsPos.x - clientWidth * 0.1
  238. moveTranslateXNum(smoothAnimationState.translateXNum)
  239. } else if (right > clientWidth * 0.85) {
  240. const osdmScrollDomScrollLeft = smoothAnimationState.osdmScrollDom?.scrollLeft || 0
  241. const maxTranslateXNum = smoothAnimationState.canvasDomWith - smoothAnimationState.osdmScrollDomWith - osdmScrollDomScrollLeft
  242. // 当还能翻页时候触发
  243. if (maxTranslateXNum > smoothAnimationState.translateXNum) {
  244. smoothAnimationState.translateXNum += clientWidth * 0.8 - state.times[0].bbox?.x
  245. if (smoothAnimationState.translateXNum > maxTranslateXNum) {
  246. smoothAnimationState.translateXNum = maxTranslateXNum
  247. }
  248. smoothAnimationState.pageTurnLock = true
  249. moveTranslateXNum(smoothAnimationState.translateXNum)
  250. }
  251. }
  252. }
  253. /**
  254. * 谱面移动逻辑
  255. */
  256. function move_osmd(nowPointsPos: pointsPosType[0]) {
  257. // 评测移动太快看不到前面小节的分数,评测改成0.5倍速移动谱面
  258. const speed = (state.modeType === "evaluating" ? smoothAnimationState.aveSpeed * 0.5 : smoothAnimationState.aveSpeed) * (state.speed / 60)
  259. // 视口宽度
  260. const clientWidth = smoothAnimationState.osdmScrollDomWith
  261. const clientMidWidth = clientWidth / 2
  262. let { left, right, width } = smoothAnimationState.smoothBotDom!.getBoundingClientRect()
  263. left -= smoothAnimationState.osdmScrollDomOffsetLeft
  264. right -= smoothAnimationState.osdmScrollDomOffsetLeft
  265. const midBotNum = left + width / 2
  266. // 分阶段移动
  267. if (right > clientWidth) {
  268. // 移动超过屏幕时候
  269. smoothAnimationState.translateXNum = 0
  270. smoothAnimationState.osdmScrollDom!.scrollLeft = nowPointsPos.x - clientWidth * 0.9
  271. } else if (left < 0) {
  272. // 移动小于屏幕时候
  273. smoothAnimationState.translateXNum = 0
  274. smoothAnimationState.osdmScrollDom!.scrollLeft = nowPointsPos.x - clientWidth * 0.1
  275. } else if (midBotNum > clientMidWidth - clientWidth * 0.3 && midBotNum <= clientMidWidth - clientWidth * 0.25) {
  276. smoothAnimationState.translateXNum += speed * 0.5
  277. } else if (midBotNum > clientMidWidth - clientWidth * 0.25 && midBotNum <= clientMidWidth - clientWidth * 0.2) {
  278. smoothAnimationState.translateXNum += speed * 0.6
  279. } else if (midBotNum > clientMidWidth - clientWidth * 0.2 && midBotNum <= clientMidWidth - clientWidth * 0.15) {
  280. smoothAnimationState.translateXNum += speed * 0.7
  281. } else if (midBotNum > clientMidWidth - clientWidth * 0.15 && midBotNum <= clientMidWidth - clientWidth * 0.1) {
  282. smoothAnimationState.translateXNum += speed * 0.8
  283. } else if (midBotNum > clientMidWidth - clientWidth * 0.1 && midBotNum <= clientMidWidth - clientWidth * 0.05) {
  284. smoothAnimationState.translateXNum += speed * 0.9
  285. } else if (midBotNum > clientMidWidth - clientWidth * 0.05 && midBotNum <= clientMidWidth) {
  286. smoothAnimationState.translateXNum += speed
  287. } else if (midBotNum > clientMidWidth && midBotNum <= clientMidWidth + clientWidth * 0.05) {
  288. smoothAnimationState.translateXNum += speed * 1.2
  289. } else if (midBotNum > clientMidWidth + clientWidth * 0.05 && midBotNum <= clientMidWidth + clientWidth * 0.1) {
  290. smoothAnimationState.translateXNum += speed * 1.4
  291. } else if (midBotNum > clientMidWidth + clientWidth * 0.1 && midBotNum <= clientMidWidth + clientWidth * 0.15) {
  292. smoothAnimationState.translateXNum += speed * 1.7
  293. } else if (midBotNum > clientMidWidth + clientWidth * 0.15 && midBotNum <= clientMidWidth + clientWidth * 0.2) {
  294. smoothAnimationState.translateXNum += speed * 2
  295. } else if (midBotNum > clientMidWidth + clientWidth * 0.2 && midBotNum <= clientMidWidth + clientWidth * 0.25) {
  296. smoothAnimationState.translateXNum += speed * 2.4
  297. } else if (midBotNum > clientMidWidth + clientWidth * 0.25 && midBotNum <= clientMidWidth + clientWidth * 0.3) {
  298. smoothAnimationState.translateXNum += speed * 2.8
  299. } else if (midBotNum > clientMidWidth + clientWidth * 0.3 && midBotNum <= clientMidWidth + clientWidth * 0.35) {
  300. smoothAnimationState.translateXNum += speed * 3.3
  301. } else if (midBotNum > clientMidWidth + clientWidth * 0.35 && midBotNum <= clientMidWidth + clientWidth * 0.4) {
  302. smoothAnimationState.translateXNum += speed * 3.8
  303. } else if (midBotNum > clientMidWidth + clientWidth * 0.4 && midBotNum <= clientMidWidth + clientWidth * 0.45) {
  304. smoothAnimationState.translateXNum += speed * 4.4
  305. } else if (midBotNum > clientMidWidth + clientWidth * 0.45 && midBotNum <= clientMidWidth + clientWidth * 0.5) {
  306. smoothAnimationState.translateXNum += speed * 5
  307. }
  308. // 最多移动的位置
  309. const osdmScrollDomScrollLeft = smoothAnimationState.osdmScrollDom?.scrollLeft || 0
  310. const maxTranslateXNum = smoothAnimationState.canvasDomWith - smoothAnimationState.osdmScrollDomWith - osdmScrollDomScrollLeft
  311. if (smoothAnimationState.translateXNum > maxTranslateXNum) {
  312. smoothAnimationState.translateXNum = maxTranslateXNum
  313. }
  314. moveTranslateXNum(smoothAnimationState.translateXNum)
  315. }
  316. /**
  317. * 根据 translateXNum 滚动到位置
  318. */
  319. export function moveTranslateXNum(translateXNum: number) {
  320. // translateXNum为0的时候不触发过度动画
  321. if (translateXNum === 0) {
  322. smoothAnimationState.osmdCanvasPageDom && (smoothAnimationState.osmdCanvasPageDom.style.transition = `none`)
  323. smoothAnimationState.selectionBoxDom && (smoothAnimationState.selectionBoxDom.style.transition = `none`)
  324. smoothAnimationState.selectionBgBoxDom && (smoothAnimationState.selectionBgBoxDom.style.transition = `none`)
  325. smoothAnimationState.osmdCanvasPageDom && (smoothAnimationState.osmdCanvasPageDom.style.transform = `translateX(-${translateXNum}px)`)
  326. smoothAnimationState.selectionBoxDom && (smoothAnimationState.selectionBoxDom.style.transform = `translateX(-${translateXNum}px)`)
  327. smoothAnimationState.selectionBgBoxDom && (smoothAnimationState.selectionBgBoxDom.style.transform = `translateX(-${translateXNum}px)`)
  328. smoothAnimationState.smoothBotDom?.offsetHeight
  329. smoothAnimationState.osmdCanvasPageDom && (smoothAnimationState.osmdCanvasPageDom.style.transition = "")
  330. smoothAnimationState.selectionBoxDom && (smoothAnimationState.selectionBoxDom.style.transition = "")
  331. smoothAnimationState.selectionBgBoxDom && (smoothAnimationState.selectionBgBoxDom.style.transition = "")
  332. smoothAnimationState.pageTurnLock = false
  333. } else {
  334. smoothAnimationState.osmdCanvasPageDom && (smoothAnimationState.osmdCanvasPageDom.style.transform = `translateX(-${translateXNum}px)`)
  335. smoothAnimationState.selectionBoxDom && (smoothAnimationState.selectionBoxDom.style.transform = `translateX(-${translateXNum}px)`)
  336. smoothAnimationState.selectionBgBoxDom && (smoothAnimationState.selectionBgBoxDom.style.transform = `translateX(-${translateXNum}px)`)
  337. }
  338. }
  339. /**
  340. * 进度条和块移动方法
  341. */
  342. function smoothAnimationMove(pos: { x: number; y: number }, progresspointsPos: pointsPosType) {
  343. smoothAnimationState.smoothBotDom && (smoothAnimationState.smoothBotDom.style.transform = `translate(${pos.x}px, ${pos.y}px)`)
  344. smoothAnimationState.canvasCtx && drawSmoothCurveProgress(smoothAnimationState.canvasCtx, progresspointsPos, "#36CFB3")
  345. }
  346. /**
  347. * 创建dom
  348. */
  349. function createSmoothAnimation() {
  350. // osdmScrollDom
  351. const osdmScrollDom = document.querySelector("#musicAndSelection") as HTMLElement
  352. smoothAnimationState.osdmScrollDom = osdmScrollDom
  353. // osmdCanvasPage
  354. const osmdCanvasPageDom = document.querySelector("#osmdCanvasPage1") as HTMLElement
  355. smoothAnimationState.osmdCanvasPageDom = osmdCanvasPageDom
  356. smoothAnimationState.osmdCanvasPageDom.addEventListener("transitionend", () => {
  357. smoothAnimationState.pageTurnLock = false
  358. })
  359. // selectionBox
  360. setTimeout(() => {
  361. const selectionBoxDom = document.querySelector("#selectionBox") as HTMLElement
  362. const selectionBgBoxDom = document.querySelector("#selectionBgBox") as HTMLElement
  363. smoothAnimationState.selectionBoxDom = selectionBoxDom
  364. smoothAnimationState.selectionBgBoxDom = selectionBgBoxDom
  365. }, 0)
  366. // box
  367. const smoothAnimationBoxDom = document.createElement("div")
  368. smoothAnimationBoxDom.className = "smoothAnimationBox smoothAnimationBoxHide"
  369. smoothAnimationState.smoothAnimationBoxDom = smoothAnimationBoxDom
  370. // con
  371. const smoothAnimationConDom = document.createElement("div")
  372. smoothAnimationConDom.className = "smoothAnimationCon"
  373. //canvas
  374. const smoothCanvasDom = document.createElement("canvas")
  375. smoothCanvasDom.className = "smoothCanvas"
  376. smoothAnimationState.canvasDom = smoothCanvasDom
  377. smoothAnimationState.canvasDomWith = osmdCanvasPageDom?.offsetWidth || 0
  378. smoothCanvasDom.width = smoothAnimationState.canvasDomWith
  379. smoothCanvasDom.height = smoothAnimationState.canvasDomHeight
  380. const ctx = smoothCanvasDom.getContext("2d")!
  381. smoothAnimationState.canvasCtx = ctx
  382. ctx.imageSmoothingEnabled = true
  383. ctx.lineCap = "round"
  384. ctx.lineJoin = "round"
  385. // bot
  386. const smoothBotDom = document.createElement("div")
  387. smoothBotDom.className = "smoothBot"
  388. smoothAnimationState.smoothBotDom = smoothBotDom
  389. // 添加小鸟
  390. render(h(Bird), smoothBotDom)
  391. smoothAnimationConDom.appendChild(smoothCanvasDom)
  392. smoothAnimationConDom.appendChild(smoothBotDom)
  393. smoothAnimationBoxDom.appendChild(smoothAnimationConDom)
  394. // 添加到 osmdCanvasPage1
  395. osmdCanvasPageDom?.insertBefore(smoothAnimationBoxDom, osmdCanvasPageDom.firstChild)
  396. }
  397. /**
  398. * 计算视口宽度
  399. */
  400. export function calcClientWidth() {
  401. smoothAnimationState.osdmScrollDomWith = smoothAnimationState.osdmScrollDom?.offsetWidth || 0
  402. smoothAnimationState.osdmScrollDomOffsetLeft = smoothAnimationState.osdmScrollDom?.getBoundingClientRect().left || 0
  403. }
  404. /**
  405. * 根据音符获取坐标
  406. */
  407. function getPointsPosByBatePos(): pointsPosType {
  408. // 得到音符频率数据
  409. const frequencyData = state.times.map(item => {
  410. return !item.frequency || item.frequency === -1 ? 0 : item.frequency
  411. })
  412. // 线性频率数据
  413. const frequencyLineData = quantileScale(frequencyData, 8, _canvasDomHeight - 8) // 最小值和最大值
  414. const pointsPos = state.times.reduce((posArr: any[], item, index) => {
  415. // 当休止小节,可能当前音符在谱面上没有实际的音符(没有bbox)
  416. if (item.bbox?.x != null && ![-Infinity, Infinity].includes(item.bbox?.x) && item.noteId != null) {
  417. posArr.push({
  418. noteId: item.noteId,
  419. MeasureNumberXML: item.MeasureNumberXML,
  420. x: item.bbox.x,
  421. y: _canvasDomHeight - frequencyLineData[index]
  422. })
  423. } else {
  424. // 连续休止小节 noteId 可能为 null,所以这里取上一个音符的id
  425. posArr.push({
  426. // 这里当第一个音符noteId为null,找不到前一个noteId,所以兼容一下
  427. noteId: item.noteId != null ? item.noteId : (posArr[posArr.length - 1]?.noteId != null ? posArr[posArr.length - 1]?.noteId : -1) + 0.01, // 这里+0.01 是制造一个假id
  428. MeasureNumberXML: item.MeasureNumberXML,
  429. x: item.bbox?.x != null && ![-Infinity, Infinity].includes(item.bbox?.x) ? item.bbox.x : posArr[posArr.length - 1]?.x || 10,
  430. y: _canvasDomHeight - frequencyLineData[index]
  431. })
  432. }
  433. return posArr
  434. }, [])
  435. // 最后一个音符延长(这里建立一个虚拟的音符延长)
  436. const extendPoint = {
  437. ...pointsPos[pointsPos.length - 1]
  438. }
  439. extendPoint.MeasureNumberXML += 100 // 防止MeasureNumberXML重复
  440. extendPoint.noteId += 100 // 防止noteId重复
  441. // 当总长度减20 和 最后一个音符加 10 取最大值 34是一倍的边距
  442. extendPoint.x = Math.max(smoothAnimationState.canvasDomWith - 34 * state.zoom - 20, extendPoint.x + 10)
  443. pointsPos.push(extendPoint)
  444. return pointsPos
  445. }
  446. // 数据平滑算法
  447. function quantileScale(data: number[], minRange = 0, maxRange = _canvasDomHeight) {
  448. const sortedData = [...data].sort((a, b) => a - b)
  449. return data.map(value => {
  450. const rank = sortedData.indexOf(value) / (sortedData.length - 1)
  451. const scaledValue = rank * (maxRange - minRange) + minRange
  452. return Math.max(minRange, Math.min(scaledValue, maxRange))
  453. })
  454. }
  455. /**
  456. * 使用传入的曲线的顶点坐标创建平滑曲线的顶点。
  457. * @param {Array} points 曲线顶点坐标数组,
  458. * @param {Int} numberOfSegments 平滑曲线 2 个顶点间的线段数
  459. * @return {Array} 平滑曲线的顶点坐标数组
  460. */
  461. function createSmoothCurvePoints(points: pointsPosType, numSegments: number) {
  462. if (points.length <= 2) {
  463. return points
  464. }
  465. const curvePoints = []
  466. for (let i = 0; i < points.length - 1; i++) {
  467. const p0 = i > 0 ? points[i - 1] : points[i]
  468. const p1 = points[i]
  469. const p2 = points[i + 1]
  470. const p3 = i !== points.length - 2 ? points[i + 2] : points[i + 1]
  471. for (let j = 0; j < numSegments; j++) {
  472. const t = j / numSegments
  473. const t2 = t * t
  474. const t3 = t2 * t
  475. const x = 0.5 * (2 * p1.x + (-p0.x + p2.x) * t + (2 * p0.x - 5 * p1.x + 4 * p2.x - p3.x) * t2 + (-p0.x + 3 * p1.x - 3 * p2.x + p3.x) * t3)
  476. const y = 0.5 * (2 * p1.y + (-p0.y + p2.y) * t + (2 * p0.y - 5 * p1.y + 4 * p2.y - p3.y) * t2 + (-p0.y + 3 * p1.y - 3 * p2.y + p3.y) * t3)
  477. curvePoints.push({ x, y, MeasureNumberXML: p1.MeasureNumberXML, noteId: p1.noteId })
  478. }
  479. }
  480. return curvePoints
  481. }
  482. /** 初始化一条完整的旋律线dom */
  483. function initCanvasSmooth() {
  484. const smoothDom = document.createElement("canvas")
  485. smoothDom.width = smoothAnimationState.canvasDomWith
  486. smoothDom.height = smoothAnimationState.canvasDomHeight
  487. const smoothDomCtx = smoothDom.getContext("2d")!
  488. smoothDomCtx.imageSmoothingEnabled = true
  489. smoothDomCtx.lineCap = "round"
  490. smoothDomCtx.lineJoin = "round"
  491. // 根据坐标花线
  492. const defaultColor = "#D0D8D6";
  493. drawLines(smoothDomCtx, smoothAnimationState.pointsPos, defaultColor)
  494. smoothAnimationState.canvasSmoothDom = smoothDom
  495. }
  496. /**
  497. * 根据进度画线
  498. */
  499. function drawSmoothCurveProgress(context: CanvasRenderingContext2D, pointsPos: pointsPosType, color: string) {
  500. context.clearRect(0, 0, smoothAnimationState.canvasDomWith, smoothAnimationState.canvasDomHeight)
  501. smoothAnimationState.canvasSmoothDom && context.drawImage(smoothAnimationState.canvasSmoothDom, 0, 0)
  502. drawLines(context, pointsPos, color)
  503. }
  504. /**
  505. * 根据坐标划线
  506. */
  507. function drawLines(context: CanvasRenderingContext2D, pointsPos: pointsPosType, color: string) {
  508. if (pointsPos.length === 0) return
  509. context.lineWidth = 2
  510. context.strokeStyle = color
  511. context.beginPath()
  512. // 记录上一个实际绘制的点
  513. let lastDrawnPoint = pointsPos[0]
  514. context.moveTo(lastDrawnPoint.x, lastDrawnPoint.y)
  515. for (let i = 1; i < pointsPos.length; i++) {
  516. const currPoint = pointsPos[i]
  517. const distance = Math.hypot(currPoint.x - lastDrawnPoint.x, currPoint.y - lastDrawnPoint.y)
  518. // 如果两个点之间的距离大于阈值,才进行绘制
  519. if (distance > 2) {
  520. context.lineTo(currPoint.x, currPoint.y)
  521. lastDrawnPoint = currPoint // 更新上一个实际绘制的点
  522. }
  523. }
  524. context.stroke()
  525. }