SOURCE

console 命令行工具 X clear

                    
>
console
/**
 * 该方法在计算文字长度的时候不够完美,用的多的话建议用overlay代替
 */

const vector=new ol.layer.Vector({
    source:new ol.source.Vector()
});

const map = new ol.Map({
    target: 'map',
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM()
        }),
        vector
    ],
    view: new ol.View({
        center: ol.proj.fromLonLat([116.39123296750768, 39.907180309385694]),
        zoom: 8
    })
});

const feature = new ol.Feature({
    geometry: new ol.geom.Point(new ol.proj.fromLonLat([116.39123296750768, 39.907180309385694]))
});
feature.setStyle(createRectStyle("华严北里"));

vector.getSource().addFeature(feature)


function createRectStyle(text) {
    let canvas, context, length;
    canvas = document.createElement("canvas");
    context = canvas.getContext("2d");
    length = text.replace(/[\u0391-\uFFE5]/g,"aa").length + 3
    canvas.width = length * 6;
    canvas.height = 12 + 8;
    let x = 0, y = 0, w = canvas.width, h = canvas.height, r = 8;
    if (w < 2 * r) r = w / 2;
    if (h < 2 * r) r = h / 2;
    context.beginPath();
    context.moveTo(x + r, y);
    context.arcTo(x + w, y, x + w, y + h, r);
    context.arcTo(x + w, y + h, x, y + h, r);
    context.arcTo(x, y + h, x, y, r);
    context.arcTo(x, y, x + w, y, r);
    context.closePath();
    context.fillStyle = "rgba(108,159,67,1)";
    context.fill();
    return new ol.style.Style({
        image: new ol.style.Icon({
            img: canvas,
            imgSize: [w, h]
        }),
        text: new ol.style.Text({
            text: text,
            font: "12px 微软雅黑",
            fill: new ol.style.Fill({ color: "#ffffff" })
        })
    });
}
<div id="map"></div>
html,body {
    margin: 0;
    padding: 0;
    height: 100%;
}

#map {
    height: 100%;
    width: 100%;
}

本项目引用的自定义外部资源