4

Is there any convenient way to change the opacity of a ol.style.Fill or ol.style.Stroke Object?

As far as I understand it, there are 2 ways to define a color with an opacity.

fill.color = [255,0,0,myOpcitay];

or

fill.color = 'rgba(255, 0,0,myOpacity)';

But what If I get a color attribute in hex format, like

var color = myStyle.getFill().getColor() // color #FF0000;

Do I really have to decompose the hex color definition in order to add the opacity? There must be a more user-friendly way to achieve this...

  • OpenLayers seems to return the same format which was used to set the style. So if you need to change one component always use an array, – Mike Jul 18 at 14:49
3

You can use ol.color.asArray method for that. Fourth element of array is then opacity:

var color = myStyle.getFill().getColor();
var colorArray = ol.color.asArray(color);
var opacity = colorArray[3];

EDIT: As Mike rightfully pointed out, above code is suitable only for reading opacity. Since asArray() method returns cached color, if we want to change color and use it independantly, copy of the color has to be created with slice() method (Mike's code):

var color = myStyle.getFill().getColor();
var colorArray = ol.color.asArray(color).slice();
colorArray[3] = 0.5;
myStyle.getFill().setColor(colorArray);
  • 3
    The API mentions the array is cached so be sure to clone it using slice otherwise you might change all red styles to semi transparent red. var colorArray = ol.color.asArray(color).slice(); colorArray[3] = 0.5; myStyle.getFill().setColor(colorArray); – Mike Jul 18 at 15:14
1

Would a 8-digit hex-code work?

See also:

Have also a look at this page:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.