bernii / gauge.js

100% native and cool looking JavaScript gauge
MIT License
1.42k stars 391 forks source link

Added text labels instead of just numeric labels #269

Open Dougie777 opened 11 months ago

Dougie777 commented 11 months ago

I dont have time to fork this so I will just post the fixed code here and a link to a working jsfiddle. UPDATE. I added the ability to put "bold" in the font string.

Working JS Fiddle: https://jsfiddle.net/L2v5rh8k/ New version with bold font support https://jsfiddle.net/7ntgfLo3/3/

Sorry guys I am in a hurry so I just plunked the compiled javascript into the jsfiddle. But I would rather share than not.

Update this function as below in the coffee script:

renderStaticLabels: (staticLabels, w, h, radius) ->
    @ctx.save()
    @ctx.translate(w, h)

    # Scale font size the hard way - assuming size comes first.
    setFont = (font) =>
        isBold = /bold/i.test(font)
        re = /\d+\.?\d?/
        match = font.match(re)[0]
        rest = font.slice(match.length).replace(/bold/i, '').trim() # Remove 'bold' from the rest
        fontsize = parseFloat(match) * @displayScale
        if isBold
            @ctx.font = "bold " + fontsize + rest
        else
            @ctx.font = fontsize + rest

    font = staticLabels.font or "10px Times"
    setFont(font)
    @ctx.fillStyle = staticLabels.color || "#000000"

    @ctx.textBaseline = "bottom"
    @ctx.textAlign = "center"
    for value in staticLabels.labels
        # Determine if the label is an object with 'label' and 'text' properties or a direct numerical value
        if (value.label == undefined)
            # Draw labels depending on limitMin/Max
            if (not @options.limitMin or value >= @minValue) and (not @options.limitMax or value <= @maxValue)
                rotationAngle = @getAngle(value) - 3 * Math.PI / 2
                @ctx.rotate(rotationAngle)
                @ctx.fillText(formatNumber(value, staticLabels.fractionDigits), 0, -radius - @lineWidth / 2)
                @ctx.rotate(-rotationAngle)
        else
            if typeof value == 'object'
                displayValue = value.label
                displayText = value.text || value.label.toString()
                font = value.font || staticLabels.font
            else
                displayValue = value
                displayText = value.toString()
                font = staticLabels.font

            # Set font with potential bold option
            setFont(font)

            # Draw labels depending on limitMin/Max
            if (not @options.limitMin or displayValue >= @minValue) and (not @options.limitMax or displayValue <= @maxValue)
                rotationAngle = @getAngle(displayValue) - 3 * Math.PI / 2
                @ctx.rotate(rotationAngle)
                @ctx.fillText(formatNumber(displayText, staticLabels.fractionDigits), 0, -radius - @lineWidth / 2)
                @ctx.rotate(-rotationAngle)

    @ctx.restore()