Elieder Elieder - 2 months ago 6
C++ Question

How to simulate a lighter effect like Canvas globalCompositeOperation does?

Every end of year I make a fireworks display Canvas effect (Javascript), the last was:

http://js1k.com/2011-dysentery/demo/955

This effect is simple: a lot of circles filled with createRadialGradient() method, with some transparency. The secret, is the property:

globalCompositeOperation = "lighter";


When used, all the colors are mixed giving the sensation of light. This year, I want to make the same, but in SFML/C++. I'm begginer in SFML and have no idea where to start making this effect. Can anyone show me how to simulate Canvas globalCompositeOperation() in SFML?

Answer

You can get this effect with a sf::Blend::Mode. See this example:

    #include <SFML/Graphics.hpp>

    int main()
    {
        sf::RenderWindow window(sf::VideoMode(400, 400), "Blend::Mode Sample");
        sf::Shape square = sf::Shape::Rectangle(100, 100, 200, 200, sf::Color(250, 30, 30));
        sf::Shape circle1 = sf::Shape::Circle(100, 100, 50, sf::Color(30, 30, 250));
        sf::Shape circle2 = sf::Shape::Circle(300, 100, 50, sf::Color(30, 30, 250));
        sf::Shape circle3 = sf::Shape::Circle(100, 300, 50, sf::Color(30, 30, 250));
        sf::Shape circle4 = sf::Shape::Circle(300, 300, 50, sf::Color(30, 30, 250));
        circle1.SetBlendMode(sf::Blend::Alpha);
        circle2.SetBlendMode(sf::Blend::Add);
        circle3.SetBlendMode(sf::Blend::Multiply);
        circle4.SetBlendMode(sf::Blend::None);
        while (window.IsOpened())
        {
            sf::Event event;
            while (window.PollEvent(event))
                if (event.Type == sf::Event::Closed)
                    window.Close();

            window.Clear();
            window.Draw(square);
            window.Draw(circle1);
            window.Draw(circle2);
            window.Draw(circle3);
            window.Draw(circle4);
            window.Display();
        }
    }

The output:

I think the effect you want would be SetBlendMode(sf::Blend::Add).