Skip to content

Commit

Permalink
Fix: handle devicePixelRatio < 1 (#3774)
Browse files Browse the repository at this point in the history
  • Loading branch information
katspaugh authored Jul 3, 2024
1 parent 057de39 commit 712e868
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
2 changes: 1 addition & 1 deletion examples/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const wavesurfer = WaveSurfer.create({
container: document.body,
waveColor: 'rgb(200, 0, 200)',
progressColor: 'rgb(100, 0, 100)',
url: '/examples/audio/audio.wav',
url: '/examples/audio/demo.wav',
})

wavesurfer.on('click', () => {
Expand Down
14 changes: 9 additions & 5 deletions src/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,10 @@ class Renderer extends EventEmitter<RendererEvents> {
return gradient
}

private getPixelRatio() {
return Math.max(1, window.devicePixelRatio || 1)
}

private renderBarWaveform(
channelData: Array<Float32Array | number[]>,
options: WaveSurferOptions,
Expand All @@ -349,7 +353,7 @@ class Renderer extends EventEmitter<RendererEvents> {

const { width, height } = ctx.canvas
const halfHeight = height / 2
const pixelRatio = window.devicePixelRatio || 1
const pixelRatio = this.getPixelRatio()

const barWidth = options.barWidth ? options.barWidth * pixelRatio : 1
const barGap = options.barGap ? options.barGap * pixelRatio : options.barWidth ? barWidth / 2 : 0
Expand Down Expand Up @@ -479,7 +483,7 @@ class Renderer extends EventEmitter<RendererEvents> {
canvasContainer: HTMLElement,
progressContainer: HTMLElement,
) {
const pixelRatio = window.devicePixelRatio || 1
const pixelRatio = this.getPixelRatio()
const canvas = document.createElement('canvas')
canvas.width = Math.round(width * pixelRatio)
canvas.height = Math.round(height * pixelRatio)
Expand Down Expand Up @@ -514,12 +518,12 @@ class Renderer extends EventEmitter<RendererEvents> {
canvasContainer: HTMLElement,
progressContainer: HTMLElement,
) {
const pixelRatio = window.devicePixelRatio || 1
const pixelRatio = this.getPixelRatio()
const { clientWidth } = this.scrollContainer

// Render a single canvas if it fits in the viewport
if (clientWidth * pixelRatio >= width) {
this.renderSingleCanvas(channelData, options, width, height, 0, canvasContainer, progressContainer)
this.renderSingleCanvas(channelData, options, clientWidth, height, 0, canvasContainer, progressContainer)
return
}

Expand Down Expand Up @@ -625,7 +629,7 @@ class Renderer extends EventEmitter<RendererEvents> {
}

// Determine the width of the waveform
const pixelRatio = window.devicePixelRatio || 1
const pixelRatio = this.getPixelRatio()
const parentWidth = this.scrollContainer.clientWidth
const scrollWidth = Math.ceil(audioData.duration * (this.options.minPxPerSec || 0))

Expand Down

0 comments on commit 712e868

Please sign in to comment.