bernii / gauge.js

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

Feature: Automatic rerendering on resize #272

Open kplindegaard opened 3 weeks ago

kplindegaard commented 3 weeks ago

Work in progress

Introduction

It is somewhat inconvenient that the gauge/donut does not adapt to the element it is included in. Therefore it is not straight-forward to use gauge.js in responsive pages. Even though #64 tries to deal with this upon creation, we would like it to happen dynamically as well. Also, some of the later improvements make a bit harder to find the best scaling approach.

This PR is an attempt to support automatic rescaling and rerendering as the page or parent element changes size. It uses the ResizeObserver pattern that was introduced around 2021 and is supported by all browsers. If used in older, deprecated browsers where ResizeObserver is not available, resizing will not be possible.

Details

This PR potentially introduces breaking changes.

Using ResizeObserver, the code will automatically attach a handler for resizing events at creation of both Gauge and Donut objects and should thus work for both. In order for it to work properly, be aware of:

  1. Each <canvas> element MUST be assigned a unique id. For example `.
  2. If used in rich SPA's, you must upon clean-up/destruction of resources remember to "detach" the observer by calling the detachAll() method on each gauge/donut object.

Regarding point 2 above:

// Construction and setup
var target = document.getElementById('foo'); // your canvas element
var gauge = new Gauge(target).setOptions(opts);
gauge.set(80); // set actual value

// ... A lot happens in the meantime, but when you clean up your resources
gauge.detachAll();

More details coming later. For now note:

  1. Sorry about the mess-up with the commits. Hadn't updated from remote in a very long time. Should not be a problem when/if the PR is squash-merged.
  2. Will try to squash a couple of minor bugs while at it.