Setting Vector Feature Fill Opacity when you have a hexadecimal color
Asked Answered
C

4

13

I'm trying to set the fill opacity of a vector feature in OL3 and can't figure out how to do it if I have a hexadecimal value...I've seen examples with rgba. Any suggestions?

Here's what I have:

style : function(feature, resolution) {
          return [new ol.style.Style(
          {
            stroke : new ol.style.Stroke(
            {
              color : feature.get('color'),  
              width : 2
            }),
            fill : new ol.style.Fill(
            {
              color : feature.get('color'), //'#FF0000'
              opacity : 0.2   // I thought this would work, but it's not an option
            })
          })]
        }
Crusty answered 17/1, 2015 at 20:46 Comment(0)
P
16

You can use the ol.color.asArray function. That function converts color strings to color arrays.

So this is what you can use:

var hexColor = feature.get('color');
var color = ol.color.asArray(hexColor);
color = color.slice();
color[3] = 0.2;  // change the alpha of the color

slice() is used to create a new color array. This is to avoid corrupting the "color strings to color arrays" cache that the ol.color.asArray function maintains.

See http://openlayers.org/en/master/apidoc/ol.color.html?unstable=true#asArray.

Profusive answered 19/1, 2015 at 20:36 Comment(0)
K
19

This is late but might help someone. Using rgba property is also possible.

fill: new ol.style.Fill({color: 'rgba(255, 255, 0, 0.63)'}),
Kristenkristi answered 2/7, 2017 at 8:12 Comment(0)
P
16

You can use the ol.color.asArray function. That function converts color strings to color arrays.

So this is what you can use:

var hexColor = feature.get('color');
var color = ol.color.asArray(hexColor);
color = color.slice();
color[3] = 0.2;  // change the alpha of the color

slice() is used to create a new color array. This is to avoid corrupting the "color strings to color arrays" cache that the ol.color.asArray function maintains.

See http://openlayers.org/en/master/apidoc/ol.color.html?unstable=true#asArray.

Profusive answered 19/1, 2015 at 20:36 Comment(0)
F
4
import ol_color from 'ol/color';

 colorWithAlpha(color, alpha) {
    const [r, g, b] = Array.from(ol_color.asArray(color));
    return ol_color.asString([r, g, b, alpha]);
 }
Forensic answered 15/7, 2018 at 14:27 Comment(0)
L
0

after learning from the other answers, i would do it in one line:

let half_orange = ol.color.asString(
  ol.color.asArray('orange')
  .slice(0, 3).concat(0.5));
Litigate answered 4/10, 2023 at 6:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.