How to tween between two colors using three.js?

I have a three.js object that is a given color. I want to animate it smoothly to a different color. During animation, it should show only a direct gradation between the beginning and the end. That is, it should not perform animation linearly in the RGB color space. I'm not even sure that linear animation in the HSV space will also look good.

How can I get this kind of twin color on a three.js object?

+6
source share
1 answer

I have a version of this that does animation in HSV space. This is not ideal, since many different shades may appear along this path.

Three.js does not include a method for obtaining HSV values ​​from a THREE.Color . So add one:

 THREE.Color.prototype.getHSV = function() { var rr, gg, bb, h, s, r = this.r, g = this.g, b = this.b, v = Math.max(r, g, b), diff = v - Math.min(r, g, b), diffc = function(c) { return (v - c) / 6 / diff + 1 / 2; }; if (diff == 0) { h = s = 0; } else { s = diff / v; rr = diffc(r); gg = diffc(g); bb = diffc(b); if (r === v) { h = bb - gg; } else if (g === v) { h = (1 / 3) + rr - bb; } else if (b === v) { h = (2 / 3) + gg - rr; } if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } } return { h: h, s: s, v: v }; }; 

Then the motion tween is relatively simple:

 new TWEEN.Tween(mesh.material.color.getHSV()) .to({h: h, s: s, v: v}, 200) .easing(TWEEN.Easing.Quartic.In) .onUpdate( function() { mesh.material.color.setHSV(this.h, this.s, this.v); } ) .start(); 

I would be interested to know about a more perceptually natural transition.

+5
source

Source: https://habr.com/ru/post/925804/


All Articles