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...

1
  • 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, 2019 at 14:49

2 Answers 2

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);
1
  • 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, 2019 at 15:14
1

Would a 8-digit hex-code work?

See also:

Have also a look at this page:

4
  • dead link unfortunately
    – Lokomotywa
    Jul 18, 2019 at 14:41
  • link should work now :)
    – Thomas
    Jul 18, 2019 at 14:48
  • still, it is a hassle to do math on a variable that might be 'red', '#FF0000', 'rgba(255,0,0,0)' or [255,0,0,0]
    – Lokomotywa
    Jul 18, 2019 at 14:49
  • does this helps to ease the hassle: stackoverflow.com/a/28033076/42659
    – Thomas
    Jul 18, 2019 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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