openlayers 使用canvas绘制圆形头像图标

 

记录一个使用canvas 将一张图片等比缩放,裁剪为一个圆

1、原始图片
在这里插入图片描述

2、绘制后在地图中呈现的样式
在这里插入图片描述

3、设置样式的函数

/**
     * 设置Style
     */
    setStyleOnPersonLocation (feature) {
      const data = feature.values_
      var imgUrl = 'https://person_head_img/avatar.jpg'

      // 绘制圆角矩形
      let canvas = document.createElement('canvas')
      canvas.width = 80
      canvas.height = 80
      var context = canvas.getContext('2d')
      var img = new Image()
      img.src = imgUrl // 原始图片
      let w = canvas.width
      let h = canvas.height
      img.onload = function () {
        context.save()
        // context.arc(x,y,r,sAngle,eAngle,counterclockwise);
        context.arc(40, 40, 20, 0, 2 * Math.PI) // 从画布上裁剪出这个圆形
        context.clip()
        // context.drawImage(img,x,y,width,height);
        context.drawImage(img, 20, 20, 40, 40)
      }

      // 设置style
      return new Style({
        image: new Icon({
          crossOrigin: 'anonymous',
          img: canvas,
          imgSize: [w, h]
        }),
        text: new Text({
          text: data.name,
          offsetY: -26,
          scale: 0.6,
          font: '12px Microsoft YaHei',
          fill: new Fill({
            color: '#808080'
          }),
          stroke: new Stroke({
            color: '#333',
            width: 1
          })
        })
      })
    },

 

4、绘制

上面样式设置的函数写好后,这里就可以开始实例化vector , 将其添加到地图中去了

import {Vector as VectorLayer} from 'ol/layer'
import GeoJSON from 'ol/format/GeoJSON'
import VectorSource from 'ol/source/Vector'
import {Point} from 'ol/geom'
import {boundingExtent, getCenter} from 'ol/extent'
import {Style, Icon, Stroke, Text, Fill} from 'ol/style'

methods:{
    addlayerToMap(){
        const geologyData = {
          type: 'FeatureCollection',
          crs: {
            type: 'Feature'
          },
          features: [
             type: 'Feature',
             properties: 'extraData',
             id:'userId',
             geometry: {
               type: 'Point',
               coordinates: [104.050629,30.65769]
            }
         ]
        }
       let nomalSource = new VectorSource({
         features: (new GeoJSON()).readFeatures(geologyData)
       })
       this.shareLocationLayer = new VectorLayer({
         source: nomalSource,
         // style: _this.setStyleOnPersonLocation // 不能在此设置style 否则地图移动会持续触发重绘
       })
    
       this.map.addLayer(this.shareLocationLayer)
       this.shareLocationLayer.getSource().forEachFeature(featureObj => {
         featureObj.setStyle(_this.setStyleOnPersonLocation(featureObj))
       })
    }
}

 

记录记录便于查阅

posted @ 2020-08-21 16:11  奔跑的痕迹  阅读(708)  评论(0编辑  收藏  举报