JavaScript Canvas - change smoothly rgb
canvas, html, javascript
Solution
Does this do what you want?
var debug = document.querySelector("#debug"),
canvas = document.querySelector('#mycanvas'),
ctx = canvas.getContext('2d'),
red = 255,
blue = 0,
green = 179,
tm = Date.now(),
inc = 2;
function lerp(a, b, n) {
return (b - a) * n + a;
}
function animate() {
var n = (Date.now() - tm) * 0.001;
n = Math.max(0, Math.min(1, n));
red = lerp(255, 36, n) | 0;
green = lerp(179, 182, n) | 0;
blue = lerp(0, 255, n) | 0;
debug.innerText = `${red} ${green} ${blue}`;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.rect(100, 100, 100, 100);
ctx.fillStyle = `rgb(${red}, ${green}, ${blue})`;
ctx.fill();
ctx.closePath();
window.requestAnimationFrame(animate);
}
animate();
<p id="debug"></p>
<canvas id="mycanvas" width="600" height="400"></canvas>
Problem
I'm trying to change color of a rectangle from 'yellow' to 'blue'. I use for it `fillStyle` with rgb. ``` var canvas = document.getElementById('mycanvas'), ctx = document.getElementById('mycanvas').getContext('2d'), red = 255, blue = 0, green = 179, inc = 2; function animate(){ ctx.clearRect(0,0,canvas.width,canvas.height); ctx.beginPath(); ctx.rect(100, 100, 100, 100); ctx.fillStyle = 'rgb('+ red +','+ green +','+ blue +')'; ctx.fill(); ctx.closePath(); red = Math.min(Math.max(red - inc, 36)) green = Math.max(green, Math.min(182, green + inc)); blue = Math.max(blue, Math.min(255, blue + inc)); requestAnimationFrame(animate); } animate(); ``` The idea was to change valuse of rgb by adding or subtracting variable named inc (equal 2). The problem is that before rectangle reach blue, he gets also other colors (like green for example). This is because the green color will increase by only 3 units, but rest of colors still needs time to get their new values. Example: http://jsfiddle.net/f2Za8/ Is there any way to make 'green' reach its new value at the same time as the 'red' and 'blue'? How to do that?