openlayers 使用font字体创建图标的两种方法

方法一:

使用canvas画布

    function getFontIcon(fontsize,fillcolor,val){
        let canvas = document.createEletment('canvas')
        canvas.width = fontsize
        canvas.height = fontsize
        let context = canvas.getContext('2d')
        context.font = `${fontsize}px iconfont`
        context.textAlign = 'left'
        context.textBaseline = 'top'
        if(fillcolor && fillcolor!==""){
            context.fillStyle = fillcolor
            context.fillText(unescape("%u"+val),0,0) //这里val使用的是Unicode编码 e646
        return canvas.toDataURL('image/png')
    let style = new ol.style.Style({
        image:new ol.style.Icon({
            anchor:[0.5,1],
            opacity:1,
            scale:0.5,
            src:getFontIcon(14,red,'e646')
    })

方法二:

使用ol.style.Text文本创建font符号,若需要既显示符号又显示文字,则在图层样式初始化时返回多个符号即可。

 let vLayer = new ol.layer.Vector({
     source:ol.source.Vector({
         features:(new ol.format.GeoJSON()).readFeatures(data),
         style:(feature,resolution)=>{
             let style = []
             //icon 符号 这里使用的是Unicode字符
             let icon = new ol.style.Style({
                 text:new ol.style.Text({
                     font:'14px iconfot',
                     text:'%ue646',
                     offsetY:0,
                     offsetX:0,
                     fill:new ol.style.Fill({
                         color:'rgba(255,255,255,0.5)'
                     rotation:45
             style.push(icon)
             let text = new ol.style.Style({
                 text:new ol.style.Text({
                     font:'14px 微软雅黑',
                     text:resolution<=0.001023?'icon text':'', // 地图缩放到指定基本时显示text标签
                     offsetY:0,
                     offsetX:0,
                     fill:new ol.style.Fill({
                         color:'#ff0000'
                     stroke:new ol.style.Stroke({
                         color:'#fff',
                         width:2
             style.push(text)
             return style