Jan 1, 2018

Using SVG color filters

This is a follow on from my previous post about showing a sprite image using the SVG.js library. We will now add a colour filter to the image using the svg.filter.js plugin.

The color matrix is a 5 column, 4 row matrix. Each row represents an RGBA value, and each column is a multiplier for that particular colour value. Every column represents an RGBA multiplier, which intensifies (or reduces) the resulting colour value based on the original input value. The last column is just a straight value that just gets added on.

So for the following matrix:

1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0

The output image will have the exact same colour value as the input image. This is because the the RGBA multipliers simple times the input RGBA value by 1.

Here are some resources:


The following code shows off the concept.

var col = {
    x: 2,
    y: 0,
}
var draw = SVG('drawing2').size(300, 300)
var clip = draw.clip()
var rect = draw.rect(32, 32)
var image = draw.image('http://icons.iconarchive.com/icons/iconfactory/star-trek-ships/icons-390.jpg')

image.move(-1*(32+5)*col.x-5,-1*(32+5)*col.y-5);

image.filter(function(add) {
  add.colorMatrix('matrix', [ 1.0, 0,   0,   0,   0
                            , 0,   0.2, 0,   0,   0
                            , 0,   0,   0.2, 0,   0
                            , 0,   0,   0,   1.0, 0 ])
})
clip.add(rect)

image.clipWith(clip)

No comments:

Post a Comment

Thanks for contributing!! Try to keep on topic and please avoid flame wars!!