Minimalistic, animated SVG gauge. Zero dependencies

Overview

SVG Gauge

Minmalistic, configurable, animated SVG gauge. Zero dependencies

Buy me a coffee

If you like my work please consider making a small donation

ko-fi

Migration from 1.0.2

The new gauge uses a viewbox of 100x100 as opposed to previous 1000x1000. All the stroke and font values have to be adjusted accordingly in your CSS. Just divide those by 10

Demo

Check out the live demo for various options and styling tips for this gauge

Usage

HTML

<div id="cpuSpeed" class="gauge-container"></div>

CSS

.gauge-container {
  width: 150px;
  height: 150px;
  display: block;
  padding: 10px;
}
.gauge-container > .gauge .dial {
  stroke: #eee;
  stroke-width: 2;
  fill: rgba(0,0,0,0);
}
.gauge-container > .gauge .value {
  stroke: rgb(47, 227, 255);
  stroke-width: 2;
  fill: rgba(0,0,0,0);
}
.gauge-container > .gauge .value-text {
  fill: rgb(47, 227, 255);
  font-family: sans-serif;
  font-weight: bold;
  font-size: 1em;
}

Javascript

// npm install
npm install svg-gauge

// Require JS
var Gauge = require("svg-gauge");

// Standalone
var Gauge = window.Gauge;

// Create a new Gauge
var cpuGauge = Gauge(document.getElementById("cpuSpeed"), {
    max: 100,
    // custom label renderer
    label: function(value) {
      return Math.round(value) + "/" + this.max;
    },
    value: 50,
    // Custom dial colors (Optional)
    color: function(value) {
      if(value < 20) {
        return "#5ee432"; // green
      }else if(value < 40) {
        return "#fffa50"; // yellow
      }else if(value < 60) {
        return "#f7aa38"; // orange
      }else {
        return "#ef4655"; // red
      }
    }
});

// Set gauge value
cpuGauge.setValue(75);

// Set value and animate (value, animation duration in seconds)
cpuGauge.setValueAnimated(90, 1);

Options

Name Description
dialStartAngle The angle in degrees to start the dial (135)
dialEndAngle The angle in degrees to end the dial. This MUST be less than dialStartAngle (45)
radius The radius of the gauge (40)
min The minimum value for the gauge. This can be a negative value (0)
max The maximum value for the gauge (100)
label Optional function that returns a string label that will be rendered in the center. This function will be passed the current value
showValue Whether to show the value at the center of the gauge (true)
gaugeClass The CSS class of the gauge (gauge)
dialClass The CSS class of the gauge's dial (dial)
valueDialClass The CSS class of the gauge's fill (value dial) (value)
valueClass The CSS class of the gauge's text (value-text)
color (new) An optional function that can return a color for current value function(value) {}
viewBox (new) An optional string that specifies the crop region (0 0 100 100)

That's all good, but what about React?

import React, { useEffect, useRef } from "react";
import SvgGauge from "svg-gauge";

const defaultOptions = {
  animDuration: 1,
  showValue: true,
  initialValue: 0,
  max: 100
  // Put any other defaults you want. e.g. dialStartAngle, dialEndAngle, radius, etc.
};

const Gauge = props => {
  const gaugeEl = useRef(null);
  const gaugeRef = useRef(null);
  useEffect(() => {
    if (!gaugeRef.current) {
      const options = { ...defaultOptions, ...props };
      gaugeRef.current = SvgGauge(gaugeEl.current, options);
      gaugeRef.current.setValue(options.initialValue);
    }
    gaugeRef.current.setValueAnimated(props.value, 1);
  }, [props]);

  return <div ref={gaugeEl} className="gauge-container" />;
};

export default Gauge;

// to render:
const renderGauge = () => (
  <Gauge
    value={42}
    // any other options you want
  />
);

And Angular?

Ha! It's already there

Comments
  • Add TypeScript types

    Add TypeScript types

    This library is great, but it was a struggle to get going with TS. Here is what I have so far:

    declare module 'svg-gauge' {
      export interface Instance {
        setMaxValue: (max: number) => void
        setValue: (val: number) => void
        setValueAnimated: (val: number, duration: number) => void
        getValue: () => number
      }
    
      export interface Opts {
        viewBox: string
        /**
         * The angle in degrees to start the dial
         * @default 135
         */
        dialStartAngle?: number
        /** The angle in degrees to end the dial. This MUST be less than dialStartAngle
         * @default 45
         */
        dialEndAngle?: number
        /** The radius of the gauge
         * @default 40
         */
        radius?: number
        /** The minimum value for the gauge. This can be a negative value
         * @default 0
         */
        min?: number
        /** The maximum value for the gauge
         * @default 100
         */
        max?: number
        /** Getter for the label that will be rendered in the center. */
        label?: (currentValue: number) => string
        /** Whether to show the value at the center of the gauge
         * @default true
         */
        showValue?: boolean
        /** 	The CSS class of the gauge
         * @default 'gauge'
         */
        gaugeClass?: string
        /** The CSS class of the gauge's dial
         * @default 'dial'
         */
        dialClass?: string
        /** The CSS class of the gauge's fill
         * @default 'value'
         */
        valueDialClass?: string
        /** The CSS class of the gauge's text
         * @default '(value-text)'
         */
        valueClass?: string
        /**
         * An optional function that can return a color for current value
         */
        color?: (currentValue: number) => string
        /** An optional string that specifies the crop region
         * @default '(0 0 100 100)'
         */
        viewBox?: string
      }
    
      export = (element: HTMLDivElement, props: Partial<Opts>) => Instance
    }
    

    Then for usage, the provided React example converted to use these types

    import React, { FC, useEffect, useRef } from 'react'
    import SvgGauge, { Opts, Instance } from 'svg-gauge'
    
    const defaultOptions: Partial<Opts> = {
      max: 100
    }
    
    const Gauge: FC<{ value: number }> = ({ value }) => {
      const gaugeEl = useRef<HTMLDivElement>(null)
      const gaugeRef = useRef<Instance | null>(null)
      useEffect(() => {
        if (!gaugeRef.current) {
          if (!gaugeEl.current) return
          const options = { ...defaultOptions, color: (value) => value < 70 ? 'green' : 'yellow' }
          gaugeRef.current = SvgGauge(gaugeEl.current, options)
          gaugeRef.current?.setValue(1)
        }
        gaugeRef.current?.setValueAnimated(value, 1)
      }, [value])
    
      return (
        <div style={{ height: '500px', width: '500px' }}>
          <div ref={gaugeEl} className='gauge-container' style={{ position: 'relative' }}>
            <span style={{ position: 'absolute', left: '45%', bottom: '70%' }}>km/hr</span>
          </div>
        </div>
      )
    }
    

    I'm rather unfamiliar with the library, so i could be way off. This is just what I have so far and is working for my simplistic use case.

    opened by christopher-caldwell 5
  • Error: <path> attribute d: Expected number,

    Error: attribute d: Expected number, "…0 A 40 40 0 1 1 NaN NaN".

    Facing this error on instantiating svg-gauge. "Error: attribute d: Expected number, "…0 A 40 40 0 1 1 NaN NaN". " this setAttribute call is causing the error https://github.com/naikus/svg-gauge/blob/ab68cda8413d9ab716d70fde552b04ea96ce6ee0/src/gauge.js#L279

    opened by codespikey 5
  • Experiencing a ReferenceError: k is not defined (gauge.js)

    Experiencing a ReferenceError: k is not defined (gauge.js)

    I am implementing this neat svg-gauge via the wrapper that @mattlewis92 made here

    I am experiencing a ReferenceError, k is not defined when I try to run my Angular 8 app with an svg-gauge in it.

    Per the console error, it seems that this is the line of code that I am battling: https://github.com/naikus/svg-gauge/blob/master/src/gauge.js#L96

    Would you be able to modify this line (or I could create a PR..?),

    FROM

    for(k in s) {
    

    TO

    for(let k in s) {
    

    I am hoping that this will solve my problems. If you have any other advice, it will be much appreciated.

    Screenshot: image

    https://angular-ssr-example.coltenkrauter.com https://github.com/coltenkrauter/angular-ssr-example

    opened by coltenkrauter 5
  • Some nice improvements that could be useful

    Some nice improvements that could be useful

    Hello, nice component. It would be great to have this kind of features added:

    1. Usage in non square container If you set dialStartAngle to180 and dialEndAngle to 0, gauge will stay on the top half of its container. If you downsize container's height, gauge will resize. Is there any way to make it not resizable?

    2. Floating point support Is there any way to set a gauge value to a floating point number (i.e. 10.5) and have it shown?

    3. Min/Max values on dial and name/unit It would be a nice improvement to add the min/max values on dial (with option to enable/disable them and customize font/size, ...) and optionally a measurement unit near gauge value

    Thanks, Stefano

    opened by StefanoBettega 5
  • Changing color while value increase

    Changing color while value increase

    Hello,

    Is it possible to implement changing color when value displayed on the gauge gradually increase ? For example, begin from green and finish to red.

    Thank you a lot for your consideration.

    enhancement 
    opened by lutchit 5
  • Fix ios-safari issue (cannot assign style)

    Fix ios-safari issue (cannot assign style)

    Hello,

    I saw an issue with ios's Safari. The style association doesn't work on it, therefore I made a patch for this issue.

    Best regards, and thanks for your job (it's a very useful lib).

    opened by bawaaaaah 4
  • Adding attributes for svg paths.

    Adding attributes for svg paths.

    Would like to use this module but I'm using other design on our paths eg. 'stroke-linecap': 'round', 'stroke-linejoin': 'round' on the paths. I made it possible to add attributes to the SVG paths.

    Take a look and see if you like it. Or just hit me back if something should be fixed.

    There are also some problems with the formatting of your code. I'm using Webstorm and there seems to be a lot of extra tabs and spaces. Have you considered using: EditorConfig?

    opened by HejdesGit 4
  • Gauge label transform not working on Safari

    Gauge label transform not working on Safari

    The gauge label, which is svg , doesn't work (gets ignored) when we try to apply a class with a transform inside. The solution is to add the inside a group: and apply to the class the group.

    opened by cetorres 3
  • Animations not working in React

    Animations not working in React

    Hi and thanks so much for making this!!

    I was having issues getting my gauges to animate in a react project and thought maybe it was my setup. I created a codesandbox and just pasted the exact react example from the readme and the animations still do not fire.

    Animations seem to work fine in a pure JS project.

    You can check out the code sandbox here.

    Let me know if I'm doing anything wrong.

    opened by JoeRoddy 3
  • Multiple values

    Multiple values

    Hey there.

    I realize that there are no needles to display multiple values, but what would be the best way to indicate something like an average value as an indicator?

    Thanks in advance!

    opened by MartinMuzatko 3
  • Is it possible to remove the padding from within the SVG?

    Is it possible to remove the padding from within the SVG?

    Amazing work... I'm noticing that all the SVGs generated with gauges have padding within the SVG, is it possible to have the gauge use the all the space in the SVG?

    Given that the gauge currently has some random padding within the SVG it makes it near impossible to create an SVG that matches a design.

    Thanks again for this, appreciate any tips. Thanks

    opened by bhellman1 3
  • Bump decode-uri-component from 0.2.0 to 0.2.2

    Bump decode-uri-component from 0.2.0 to 0.2.2

    Bumps decode-uri-component from 0.2.0 to 0.2.2.

    Release notes

    Sourced from decode-uri-component's releases.

    v0.2.2

    • Prevent overwriting previously decoded tokens 980e0bf

    https://github.com/SamVerschueren/decode-uri-component/compare/v0.2.1...v0.2.2

    v0.2.1

    • Switch to GitHub workflows 76abc93
    • Fix issue where decode throws - fixes #6 746ca5d
    • Update license (#1) 486d7e2
    • Tidelift tasks a650457
    • Meta tweaks 66e1c28

    https://github.com/SamVerschueren/decode-uri-component/compare/v0.2.0...v0.2.1

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
  • SetMaxValue does not update the label if

    SetMaxValue does not update the label if "this.max" is used in the label

    Title says it all. Basically, I have using the configuration below for labels

    label: function(value) {
        return Math.round(value) + "/" + this.max;
    }
    

    But, when I use the setMaxValue() function there, it will not update the this.max in the label. https://github.com/naikus/svg-gauge/blob/5fd44a3f2d62a7019345bc3019a43f81693dbac5/src/gauge.js#L303-L305

    I tried to replace this.max by this.limit, as it is the internal variable, but the label shows as NaN instead. https://github.com/naikus/svg-gauge/blob/5fd44a3f2d62a7019345bc3019a43f81693dbac5/src/gauge.js#L303-L305

    opened by sharky98 2
  • Color Text Value

    Color Text Value

    Hi!

    .gauge-container.one > .gauge > .value-text { fill: rgb(47, 227, 255);
    }

    .gauge-container.three > .gauge > .value-text { fill: #C9DE3C; }

    Not working?

    opened by gledsoneduardo 0
  • Allow arbitrary values

    Allow arbitrary values

    Current implementation uses normalized values (constrained inside min/max), but this is not always desired. Eg. i use it for displaying sensor values, the gauges are constrained to display interested range, but values sometime goes out of these boundaries. All works OK, but the gauge stays to display normalized (min or max) value in label, which is false value of course.

    Please, use normalized values only for internal calculations (drawing) and allow to show real values for label.

    opened by slavkoja 2
Releases(1.0.5)
  • 1.0.5(Jan 8, 2019)

  • 1.0.4(Nov 30, 2017)

    Fixed minor bugs

    • Value dial colour now shows for initial value
    • Positive min and max values now work correctly (e.g. min: 50, max: 150)
    var gauge = Gauge( document.getElementById("gauge2"),  {
        min: 50, // +ve min value
        max: 150,
        dialStartAngle: 180,
        dialEndAngle: 0,
        value: 50, // The color is correctly shown now
        color: function(value) {
          if(value < 20) {
            return "#5ee432";
          }else if(value < 40) {
            return "#fffa50";
          }else if(value < 60) {
            return "#f7aa38";
          }else {
            return "#ef4655";
          }
        }
      }
    );
    
    Source code(tar.gz)
    Source code(zip)
  • 1.0.3(Nov 30, 2017)

  • 1.0.2(Nov 2, 2016)

  • 1.0.1(Oct 28, 2016)

  • 1.0.0(Oct 25, 2016)

    Added custom label support

    
          var gauge1 = Gauge(
            document.getElementById("gauge1"), 
                {
              max: 100,
              dialStartAngle: -90,
              dialEndAngle: -90.001, 
              value: 100,
              label: function(value) {
                return Math.round(value) + "/" + this.max;
              }
            }
          );
    
    
    Source code(tar.gz)
    Source code(zip)
Owner
Aniket Naik
G33/< & amateur barista. ❤️ Web & mobile web development, UI/UX
Aniket Naik
Simple, responsive, modern SVG Charts with zero dependencies

Frappe Charts GitHub-inspired modern, intuitive and responsive charts with zero dependencies Explore Demos » Edit at CodePen » Contents Installation U

Frappe 14.6k Jan 4, 2023
Javascript Canvas Library, SVG-to-Canvas (& canvas-to-SVG) Parser

Fabric.js Fabric.js is a framework that makes it easy to work with HTML5 canvas element. It is an interactive object model on top of canvas element. I

Fabric.js 23.6k Jan 3, 2023
Javascript Canvas Library, SVG-to-Canvas (& canvas-to-SVG) Parser

Fabric.js Fabric.js is a framework that makes it easy to work with HTML5 canvas element. It is an interactive object model on top of canvas element. I

Fabric.js 23.6k Jan 3, 2023
Data visualization library for depicting quantities as animated liquid blobs

liquidity.js A data visualization library for depicting quantities as animated liquid blobs. For a demonstration of what the final product can look li

N Halloran 91 Sep 20, 2022
Matteo Bruni 4.7k Jan 4, 2023
Highly customizable, animated, responsive, and dependency-free Evolution Graph implementation

Highly customizable, animated, responsive, and dependency-free Evolution Graph implementation. The package is built with Vanilla JavaScript and is used to create flexible data visualizations and present evolution relationships between entities.

Nathan S. Santos 39 Jan 5, 2023
Bring data to life with SVG, Canvas and HTML. :bar_chart::chart_with_upwards_trend::tada:

D3: Data-Driven Documents D3 (or D3.js) is a JavaScript library for visualizing data using web standards. D3 helps you bring data to life using SVG, C

D3 103.8k Jan 3, 2023
The JavaScript library for modern SVG graphics.

Snap.svg · A JavaScript SVG library for the modern web. Learn more at snapsvg.io. Follow us on Twitter. Install Bower - bower install snap.svg npm - n

Adobe Web Platform 13.6k Dec 30, 2022
The lightweight library for manipulating and animating SVG

SVG.js A lightweight library for manipulating and animating SVG, without any dependencies. SVG.js is licensed under the terms of the MIT License. Inst

SVG.js 10k Dec 25, 2022
Progressive pie, donut, bar and line charts

Peity Peity (sounds like deity) is a jQuery plugin that converts an element's content into a mini <svg> pie, donut, line or bar chart. Basic Usage HTM

Ben Pickles 4.2k Jan 1, 2023
Beautiful React SVG maps with d3-geo and topojson using a declarative api.

react-simple-maps Create beautiful SVG maps in react with d3-geo and topojson using a declarative api. Read the docs, or check out the examples. Why R

z creative labs 2.7k Dec 29, 2022
A lightweight JavaScript graphics library with the intuitive API, based on SVG/VML technology.

GraphicsJS GraphicsJS is a lightweight JavaScript graphics library with the intuitive API, based on SVG/VML technology. Overview Quick Start Articles

AnyChart 973 Jan 3, 2023
Flat, round, designer-friendly pseudo-3D engine for canvas & SVG

Zdog Round, flat, designer-friendly pseudo-3D engine View complete documentation and live demos at zzz.dog. Install Download zdog.dist.min.js minified

Metafizzy 9.5k Jan 3, 2023
The lightweight library for manipulating and animating SVG

SVG.js A lightweight library for manipulating and animating SVG, without any dependencies. SVG.js is licensed under the terms of the MIT License. Inst

SVG.js 10k Jan 3, 2023
A lightweight JavaScript graphics library with the intuitive API, based on SVG/VML technology.

GraphicsJS GraphicsJS is a lightweight JavaScript graphics library with the intuitive API, based on SVG/VML technology. Overview Quick Start Articles

AnyChart 937 Feb 5, 2021
📊 Interactive JavaScript Charts built on SVG

A modern JavaScript charting library to build interactive charts and visualizations with simple API. Our Partner ApexCharts is now a partner of Fusion

ApexCharts 12.1k Jan 3, 2023
A Cloudflare Worker that translates TeX to SVG

TeX SVG Worker A Cloudflare Worker that translates TeX to SVG.

JacobLinCool 6 Jan 9, 2023
📸 Generate image using HTML5 canvas and SVG

egami → image README | 中文文档 Generate image using HTML5 canvas and SVG Fork from html-to-image Installation pnpm pnpm add egami npm npm i egami Usage i

weng 12 Jan 3, 2023
JavaScript SVG parser and renderer on Canvas

canvg JavaScript SVG parser and renderer on Canvas. It takes the URL to the SVG file or the text of the SVG file, parses it in JavaScript and renders

null 3.3k Jan 4, 2023