Skip to content

Commit fe0ffdb

Browse files
authored
Convert color values from array to lineargradient (#2797)
* added convertColorValues private method * Added snapshot test for color gradient * removed undefined from function parameter types
1 parent 743e8b0 commit fe0ffdb

File tree

3 files changed

+47
-1
lines changed

3 files changed

+47
-1
lines changed

cypress/e2e/options.cy.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,33 @@ describe('WaveSurfer', () => {
9999
})
100100
})
101101

102+
it('should use gradient color options', () => {
103+
cy.window().then((win) => {
104+
return new Promise((resolve) => {
105+
win.wavesurfer = win.WaveSurfer.create({
106+
container: id,
107+
url: '../../examples/audio/demo.wav',
108+
waveColor: [
109+
"rgb(200, 165, 49)",
110+
"rgb(211, 194, 138)",
111+
"rgb(205, 124, 49)",
112+
"rgb(205, 98, 49)",
113+
],
114+
progressColor: 'rgba(0, 0, 0, 0.25)',
115+
cursorColor: 'blue',
116+
})
117+
118+
win.wavesurfer.once('ready', () => {
119+
win.wavesurfer.setTime(10)
120+
cy.wait(100)
121+
cy.snap
122+
cy.get(id).matchImageSnapshot('colors-gradient')
123+
resolve()
124+
})
125+
})
126+
})
127+
})
128+
102129
it('should use cursor options', () => {
103130
cy.window().then((win) => {
104131
return new Promise((resolve) => {
9.81 KB
Loading

src/renderer.ts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,25 @@ class Renderer extends EventEmitter<RendererEvents> {
221221
})
222222
}
223223

224+
// Convert array of color values to linear gradient
225+
private convertColorValues(color: string | string[] = "") {
226+
if (!Array.isArray(color)) return color;
227+
if (color.length < 2) return color.length === 1 ? color[0] : "";
228+
229+
const canvasElement = this.canvasWrapper.children[0] as HTMLCanvasElement;
230+
const gradient = canvasElement.getContext('2d')?.createLinearGradient(0, 0, 0, canvasElement.height) || "";
231+
232+
if (gradient) {
233+
const colorStopPercentage = 1 / (color.length - 1);
234+
color.forEach((color, index) => {
235+
const offset = index * colorStopPercentage;
236+
gradient.addColorStop(offset, color);
237+
});
238+
}
239+
240+
return gradient;
241+
}
242+
224243
private async renderPeaks(audioData: AudioBuffer, width: number, height: number, pixelRatio: number) {
225244
const barWidth =
226245
this.options.barWidth != null && !isNaN(this.options.barWidth) ? this.options.barWidth * pixelRatio : 1
@@ -260,7 +279,7 @@ class Renderer extends EventEmitter<RendererEvents> {
260279
}) as CanvasRenderingContext2D
261280

262281
ctx.beginPath()
263-
ctx.fillStyle = this.options.waveColor ?? ''
282+
ctx.fillStyle = this.convertColorValues(this.options.waveColor)
264283

265284
// Firefox shim until 2023.04.11
266285
if (!ctx.roundRect) ctx.roundRect = ctx.fillRect

0 commit comments

Comments
 (0)