since095 since095 - 6 months ago 19
Javascript Question

Update position/transition from last value (guage chart / d3.js)

I'm trying to repurpose a guage chart I found here. Currently I have the needle moving on submit, however it resets to 0 before updating to the new position, I'd rather it just adjust the position directly.

When trying to think of a way to do it, I figured that I would need to modifiy this snippet of code which handles the reset;

Needle.prototype.moveTo = function(perc) {
var self,
oldValue = this.perc || 0;

this.perc = perc;
self = this;

// Reset pointer position
this.el.transition().delay(100).ease('quad').duration(200).select('.needle').tween('reset-progress', function() {
return function(percentOfPercent) {
var progress = (1 - percentOfPercent) * oldValue;

repaintGauge(progress);
return d3.select(this).attr('d', recalcPointerPos.call(self, progress));
};
});

this.el.transition().delay(300).ease('bounce').duration(1500).select('.needle').tween('progress', function() {
return function(percentOfPercent) {
var progress = percentOfPercent * perc;

repaintGauge(progress);
return d3.select(this).attr('d', recalcPointerPos.call(self, progress));
};
});

};

return Needle;

})

();


So I think, I am going to have to find a way of remember the old value before updating instead of resetting to 0, or just try remove the reset function completely?

But I'm not really sure how I can achieve that.

Here is the update function;

function updateNeedle() {
var value = 90;
var percentValue = value / gaugeMaxValue;
percent = percentValue;
needle.moveTo(percent);
}


I have made a plnk, and tried to strip out everything not relevant to the question to reduce the code, just click the submit to update the position and hopefully the question will make sense.

https://plnkr.co/edit/NtlpGoEf5J1XRfgTjewR?p=preview

I think this all might be a bit hacky, but i'm hoping someone can help anyway!

Thanks

Answer

I changed your moveTo function. It was using progress starting from 0. So, I change to this:

var progress = oldValue + (percentOfPercent * (perc - oldValue));

Here is the plunker: https://plnkr.co/edit/RCNNpLX0Un7LzWW1YDwu?p=preview

I made this other plunker setting the value to a random number when the user clicks "submit", using var value = Math.random()*100. I believe it's working the way you want, check it: https://plnkr.co/edit/xj2sGBidjnPN5R9CkA59?p=preview