simonzack
simonzack

Reputation: 20928

Animating colors in paper.js

Is there a color delta object in paper.js, which can store negative values in each component? What I'm trying to achieve here is to animate a color to another color smoothly, by storing the color change in each frame in this color delta object.

Simply subtracting one color from another does not work, as negative values are not permitted:

var color1 = new Color(0, 1, 1);
var color2 = new Color(1, 0, 0);
var result = color1 - color2;
console.log(result); // { red: 0, blue: 1, green: 1 }

Any suggestions, including easier ways to achieve the same animation effect would be appreciated.

Upvotes: 1

Views: 1875

Answers (3)

beaslera
beaslera

Reputation: 863

There is an example on the paper.js website about animating colors. With minor modifications you could get it to animate from one color to another and then stop.

// Create a circle shaped path at the center of the view,
// with a radius of 70:
var path = new Path.Circle({
    center: view.center,
    radius: 70,
    fillColor: 'red'
});
var finalColor = new Color('blue');
function onFrame(event) {
    if (path.fillColor.hue != finalColor.hue) {
        path.fillColor.hue += 1;
    }
}

Or, if you would rather stick with RGB, how about:

var color1 = new Color(0, 1, 1);
var color2 = new Color(1, 0, 0);
var changeFrame = 0;
var maxChangeFrames = 100;
var path = new Path.Circle({
    center: view.center,
    radius: 70,
    fillColor: color1
})
function findMiddleColorComponent(comp1, comp2, percentChanged) {
    return (comp2 - comp1)*percentChanged + comp1;
}
function findMiddleRGBColor(c1, c2, percentChanged) {
    return new Color(findMiddleColorComponent(c1.red, c2.red, percentChanged),
                     findMiddleColorComponent(c1.green, c2.green, percentChanged),
                     findMiddleColorComponent(c1.blue, c2.blue, percentChanged));
}
function onFrame(event) {
    if (changeFrame < maxChangeFrames) {
        changeFrame += 1;
        path.fillColor = findMiddleRGBColor(color1, color2, changeFrame/maxChangeFrames);
    }
}

If this is the sort of thing you are looking for, my next steps would probably be to create a new object containing the circle, changeFrame, maxChangeFrames, and the two helper functions. That way all of the code used to animate the colors would be contained in that one object.

Upvotes: 4

J&#252;rg Lehni
J&#252;rg Lehni

Reputation: 1816

Yes it's a known issue that negative components are not allowed. I'm thinking of changing this and moving the clamping of values further down:

https://github.com/paperjs/paper.js/issues/271

Upvotes: 3

frederickk
frederickk

Reputation: 73

Here's an example of blending colors from one to another using my library folio.js (https://github.com/frederickk/folio.js) which extends paper.js functionality with interpolate functions (useful for cross blending colors)

http://kennethfrederick.com/folio.js/spectrum.html

Upvotes: 1

Related Questions