user669677
user669677

Reputation:

How to multiply two colors in javascript?

The given parameters are r,g,b of two colors.

How can I multiply them? (Like blending mode->multiply in Photoshop)

Example:

color1:0,255,255

color2:255,255,0

multiplied:0,255,0

example

Upvotes: 12

Views: 7840

Answers (4)

David Hellsing
David Hellsing

Reputation: 108482

Based on the simple multiply formula, here is a javascript function that should work for RGB:

function multiply(rgb1, rgb2) {
    var result = [],
        i = 0;
    for( ; i < rgb1.length; i++ ) {
        ​result.push(Math.floor(rgb1[i] * rgb2[i] / 255));
    }
    return result;
}​

Using modern JavaScript:

const multiply = (rgb1, rgb2) => rgb1.map((c, i) => Math.floor(c * rgb2[i] / 255))

Here is a fiddle using background colors you can play with: http://jsfiddle.net/unrLC/

enter image description here

Upvotes: 9

Samuel
Samuel

Reputation: 17161

Here's the formula for multiplying colors (as well as other blend mode formulas).

Formula: Result Color = (Top Color) * (Bottom Color) /255

You can implement this very easily in JavaScript.

var newRed = red1 * red2 / 255;
var newGreen = green1 * green2 / 255;
var newBlue = blue1 * blue2 / 255;

Upvotes: 8

Bergi
Bergi

Reputation: 664196

I guess the aim is to multiply color ranges from 0 to 255. Reduce them to a range of [0, 1], multiply them, and expand them again:

color_new = ( (color_1 / 255) * (color_2 / 255) ) * 255
color_new = color_1 * color_2 / 255

Upvotes: 0

Guffa
Guffa

Reputation: 700152

You translate the color components to a value between 0 and 1, then it's simple multiplication. Thanslate the result back to the range 0 to 255:

0, 255, 255  ->  0, 1, 1
255, 255, 0  ->  1, 1, 0

0*1 = 0, 1*1 = 1, 1*0 = 0

0, 1, 0  ->  0, 255, 0

Upvotes: 3

Related Questions