openlayers 使用canvas繪制圓形頭像圖標(biāo)

記錄一個(gè)使用canvas 將一張圖片等比縮放,裁剪為一個(gè)圓

1、原始圖片


在這里插入圖片描述

2、繪制后在地圖中呈現(xiàn)的樣式


在這里插入圖片描述

3、設(shè)置樣式的函數(shù)

    /**
     * 設(shè)置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) // 從畫布上裁剪出這個(gè)圓形
        context.clip()
        // context.drawImage(img,x,y,width,height);
        context.drawImage(img, 20, 20, 40, 40)
      }

      // 設(shè)置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、繪制

上面樣式設(shè)置的函數(shù)寫好后,這里就可以開始實(shí)例化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 // 不能在此設(shè)置style 否則地圖移動(dòng)會(huì)持續(xù)觸發(fā)重繪
       })
    
       this.map.addLayer(this.shareLocationLayer)
       this.shareLocationLayer.getSource().forEachFeature(featureObj => {
         featureObj.setStyle(_this.setStyleOnPersonLocation(featureObj))
       })
    }
}

記錄記錄便于查閱

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容