JavaScript画布-平滑更改RGB [英] JavaScript Canvas - change smoothly rgb

查看:72
本文介绍了JavaScript画布-平滑更改RGB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将矩形的颜色从黄色更改为蓝色。我将其与 fillStyle 。

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();

这个想法是通过添加或减去名为inc的变量(等于2)来更改rgb的值。问题在于,在矩形变为蓝色之前,他还获得了其他颜色(例如,绿色)。这是因为绿色只会增加3个单位,但是其余的颜色仍然需要时间才能获得新的值。示例:

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?

推荐答案

这是您想要的吗?

HTML:

<p id="debug"></p>
<canvas id="mycanvas" width="600" height="400"></canvas>

JS:

   var debug=document.getElementById("debug"),
        canvas = document.getElementById('mycanvas'),
        ctx = document.getElementById('mycanvas').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.innerHTML=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();

        requestAnimationFrame(animate);
    }

    animate();

这篇关于JavaScript画布-平滑更改RGB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆