开源

openlayers text多背景颜色

2022-02-19  本文已影响0人  happy_port
image.png
feature = new ol.Feature({
        geometry: new ol.geom.Point([121.359045, 31.317679]),
      });
const symbol = {
        icon: "./img/images/earthquake.png",
        scale: 0.8,
        textColor: "#fff",
        font: "14px Calibri,sans-serif",
      };
feature.setStyle(createCustomStyle("ol多背景颜色", symbol, ["rgba(153, 115, 81, 1)", "rgba(36, 215, 150, 1)", "rgba(0, 255, 0, 1)"]));
    
 function createCustomStyle(text, symbol, colors) {
        let canvas = document.createElement("canvas");
        let context = canvas.getContext("2d");
        context.font = symbol.font;
        let width = context.measureText(text).width;
        let styles = [],
          style;
        if (colors && colors.length) {
          for (let i = 0, len = colors.length; i < len; i++) {
            style = new ol.style.Style({
              text: new ol.style.Text({
                text: text,
                font: symbol.font,
                offsetX: (i * width) / len,
                offsetY: -36,
                textAlign: "center",
                textBaseline: "bottom",
                fill: new ol.style.Fill({
                  color: "rgba(255,255,255,0)",
                }),
                backgroundFill: new ol.style.Fill({
                  color: colors[i],
                }),
                padding: [4, -(i * width) / len + 4, 4, 4],
              }),
            });
            styles.push(style);
          }
        }
        style = new ol.style.Style({
          text: new ol.style.Text({
            text: text,
            font: symbol.font,
            offsetX: 0,
            offsetY: -36,
            textAlign: "center",
            textBaseline: "bottom",
            fill: new ol.style.Fill({
              color: symbol.textColor,
            }),
            padding: [4, 4, 4, 4],
          }),
          image: new ol.style.Icon({
            src: symbol.icon,
            scale: symbol.scale,
          }),
        });
        styles.push(style);

        return styles;
      }

上一篇下一篇

猜你喜欢

热点阅读